判断一个枚举值是否属于某个枚举类

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;
    }
}
/** * @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;
    }
}
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));
    }
}
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)); } }
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)); } }
经验分享 程序员 微信小程序 职场和发展