java枚举类常见操作

x33g5p2x  于2022-02-09 转载在 Java  
字(1.6k)|赞(0)|评价(0)|浏览(405)

java枚举类常见操作

public enum Status {
    OK(0, "成功"),
    ERROR_A(100, "错误A"),
    ERROR_B(200, "错误B");

    Status(int number, String description) {
        this.code = number;
        this.description = description;
    }
    private int code;
    private String description;
    public int getCode() {
        return code;
    }
    public String getDescription() {
        return description;
    }
    //根据code查找description
    public static String getValue(int v) { 
        for (Status s : Status.values()) {
            if (v==s.getCode()){
              return  s.getDescription();
            }
        }
        return "";
    }
    
    //判断Status里是否有此code
    public static boolean isInclude(String co) {
        for (OpenBusinessEnum s : OpenBusinessEnum.values()) {
           if (co.equals(s.getCode())){
               return  true;
           }
       }
       return false;
    }
    
    //获取所有的description
    public static String[] getValue() { 
       String[] arry = new String[Status.values().length];
       int i = 0;
       for (Status s : Status.values()) {
           arry[i] = s.getDescription();
           i++;
       }
       return arry;
   }

	//判断该枚举中是否含有传入的值
    public static boolean contains(String test) {
        for (Status c : Status.values()) {
            if (c.name().equals(test)) {
                return true;
            }
        }
        return false;
    }
}

测试

System.out.println(Status.getde(0));//查找Status枚举中code是0的description的值。输出:成功
 System.out.println(Status.valueOf("OK").getCode());//查找Status枚举中OK的code。输出:0
 System.out.println(Status.valueOf("OK").getDescription());//查找Status枚举中OK的description。输出:成功

System.out.println(Status.OK); //输出:OK
System.out.println(Status.OK.getCode()); //输出:0
System.out.println(Status.OK.getDescription()); //输出:成功
System.out.println(Arrays.asList(Status.getde()));//输出:[成功, 错误A, 错误B]

String event1 = "aaa";
String event2 = "ERROR_B";
System.out.println(Status.contains(event1));//false。因为Status中不含有aaa
System.out.println(Status.contains(event2));//true。因为Status中含有ERROR_B

相关文章

最新文章

更多