1. 程式人生 > >判斷一個枚舉值是否屬於某個枚舉類

判斷一個枚舉值是否屬於某個枚舉類

工具類 private param util jdk 1.7 jdk 枚舉值 是否 bsp

1:自定義枚舉類

/**
 * @Description: 控制開關的狀態
 * @since: JDK 1.7
 * @Version:  V1.0
 */
public enum SwitchStatus {
    CLOSE(0, "0-關閉"),
    OPEN(1, "1-開啟");

    private int key;
    private String value;

    private SwitchStatus(int key, String value) {
        this.key = key;
        this.value = value;
    }

    
public int getKey() { return key; } public String getValue() { return value; } }

2:工具類方法——本例的核心

public class EnumUtil {
    /**
     * 判斷數值是否屬於枚舉類的值
     * @param key
     * @return
     */
    public static boolean isInclude(int key){
        boolean include = false;
        
for (SwitchStatus e: SwitchStatus.values()){ if(e.getKey()==key){ include = true; break; } } return include; } }

3:測試

public class TestMain {
    public static void main(String[]args){
        System.out.println(EnumUtil.isInclude(
0)); System.out.println(EnumUtil.isInclude(1)); System.out.println(EnumUtil.isInclude(2)); } }

判斷一個枚舉值是否屬於某個枚舉類