枚举使用的正确姿势

版权声明:本文为博主总结文章,未经博主允许您依然可以转载。 https://blog.csdn.net/Memery_last/article/details/60868918

枚举较常量的优势

  1. 枚举可以满足使用常量的需求,
  2. 使枚举常量可以有更多的描述,(如:枚举可以使用key code desc来构造)
  3. 避免了传统常量的无范围性,(如:方法接受参数String,final可以满足,但使用枚举类型将缩小参数范围)

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)找不到枚举会抛出异常。

猜你喜欢

转载自blog.csdn.net/Memery_last/article/details/60868918