枚举属性简单获取,枚举用于状态值管理

  项目中,对于数据库状态值得管理及查询展示不一致的处理方式之一(可以sql查询阶段做case处理,也可用本文的枚举做法做简单处理)。

  

import java.util.HashMap;
import java.util.Map;

public enum Enum1 {
    STATE1(0, "有效"),
    STATE2(1, "过期"),
    STATE3(3, "无效");

    private static final Map<Integer, String> stateMap;

    static { //由类加载机制,静态块初始加载对应的枚举属性到map中,而不用每次取属性时,遍历一次所有枚举值
        stateMap = new HashMap();
        for (Enum1 enum1 : values()) {
            stateMap.put(enum1.code, enum1.description);
        }
    }

    private int code;
    private String description;

    Enum1(int code, String description) {
        this.code=code;
        this.description=description;
    }

    public static String getDesByCode(Integer code) {
        return stateMap.get(code);
    }

    public static void main(String[] args) {
    //获取code值对应的描述,同理也可以根据描述获取code值用于数据库存储。
    System.out.println(getDesByCode(1));
   }
}

  总结:项目中关于状态值得简单处理方式之一,利用类加载和枚举特性,高效查询枚举属性

猜你喜欢

转载自www.cnblogs.com/swz1104919/p/11744156.html
今日推荐