PS: 枚举本质是语法糖,具体可以参考此处了解 http://unmi.cc/understand-java-enum-with-bytecode/
先看一个枚举类代码(一个排序方式的枚举):
public enum SortType { ENUM_INVALID(-1, "ENUM_INVALID","ENUM_INVALID"), REVERSED(1, "-", "倒序"), NORMAL(2, "+", "正序"), ; private static List<SortType> sortTypeList; static { sortTypeList = Arrays.asList(REVERSED, NORMAL); } public static List<SortType> getBuyOrderSortTypeList() { return sortTypeList; } private final Integer key; private final String code; private final String desc; SortType(Integer key, String code, String desc) { this.key = key; this.code = code; this.desc = desc; } public static SortType keyOf(Integer key) { for (SortType status : SortType.values()) { if (status.key.equals(key)) { return status; } } return REVERSED; } public static SortType codeOf(String code) { for (SortType status : SortType.values()) { if (status.code.equals(code)) { return status; } } return REVERSED; } public static SortType descOf(String desc) { for (SortType status : SortType.values()) { if (status.desc.equals(desc)) { return status; } } return REVERSED; } public Integer getKey() { return key; } public String getCode() { return code; } public String getDesc() { return desc; } }几点好处: 1)入库或者前台使用Integer 的key, 2)描述丰富 key code desc, 3)keyOf codeOf descOf的查找方法,找不到则返回Enum invalid。
与原生的valueOf比较: 1)只支持使用枚举String名字的查找枚举类型, 2)找不到枚举会抛出异常。