示例1:
public enum RandomEnum
{
StartHere,
StopHere
}
//转换成list
List<RandomEnum> list = Arrays.asList(RandomEnum.values());
示例2:
public enum Status {
OK(0, "成功"),
ERROR_A(100, "错误A"),
ERROR_B(200, "错误B");
private final int code;
private final String description;
Status(int number, String description) {
this.code = number;
this.description = description;
}
// 使用 Map 提高查找效率
private static final Map<Integer, Status> STATUS_MAP = new HashMap<>();
static {
Arrays.stream(Status.values()).forEach(status -> STATUS_MAP.put(status.getCode(), status));
}
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
//根据code查找description
public static String getdesc(int code) {
Status status = STATUS_MAP.get(code);
return status != null ? status.getDescription() : "";
}
//判断Status里是否有此code
public static boolean hasCode(int code) {
return STATUS_MAP.containsKey(code);
}
//获取所有的description
public static List<String> getdesc() {
return Arrays.stream(Status.values()).map(Status::getDescription).collect(Collectors.toList());
}
//判断该枚举中是否含有传入的枚举名称
public static boolean contains(String enumName) {
if (enumName == null) {
return false;
}
try {
Status.valueOf(enumName);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}
测试:
public static void main(String[] args) {
System.out.println(Status.getdesc(0));//查找Status枚举中code是0的description的值。输出:成功
System.out.println(Status.hasCode(0));//判断Status里是否有为0的code。输出:true
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(Status.getdesc());//输出:[成功, 错误A, 错误B]
String enumName1 = "aaa";
String enumName2 = "ERROR_B";
System.out.println(Status.contains(enumName1));//输出:false。因为Status中不含有 aaa
System.out.println(Status.contains(enumName2));//输出:true。因为Status中含有 ERROR_B
}
参考文章:
Java 枚举
枚举中valueOf用法
Java Enum原理
java枚举类Enum方法简介
使用valueof前必须进行校验