java枚举变量反解析用法(将mysql的int类型映射为枚举类型)

最近常常有一些项目需要给枚举设值一个int值,以及对int值进行反解析出枚举类型,代码如下:

 1 public enum MatchResultEnum {
 2 
 3     /**
 4      * 赢
 5      */
 6     WIN(0),
 7     /**
 8      * 输
 9      */
10     LOSE(1),
11     /**
12      * 平局
13      */
14     DRAW(2);
15 
16     /**
17      * 比赛结果的code值
18      */
19     private int code;
20 
21     MatchResultEnum(int value) {
22         this.code = value;
23     }
24 
25     public int getCode() {
26         return code;
27     }
28 
29 
30     public static MatchResultEnum parse(int value) {
31         MatchResultEnum[] values = values();
32         for (MatchResultEnum matchResult : values) {
33             if (matchResult.code == value) {
34                 return matchResult;
35             }
36         }
37         return null;
38     }
39 }

后期优化如下:

1 private static MatchResultEnum[] result = {WIN, LOSE, DRAW};
2 public static MatchResultEnum parse(int value) {
3     if (value < result.length) {
4         return result[value];
5     }
6     return null;
7 }
8 
9 //替换原代码:30-38行 ,原因数组更加高效。但是这种用法有取巧的做法,前提是code值刚好是从0开始顺序递增的
另外一种方法:(前提是每个枚举的code值是唯一的)
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 告警类型
 * 目前支持邮件告警和,短信告警
 */
public enum AlarmTypeEnum {
    /**
     * 短信告警
     */
    SMS((short) 1),
    /**
     * 邮件告警
     */
    EMAIL((short) 2);

    /**
     * 数据库中存储的码号,号码不能重复
     */
    private short code;

    private static Map<Short, AlarmTypeEnum> alarmTypes;
    static {
        alarmTypes = new HashMap<>();
        AlarmTypeEnum[] values = AlarmTypeEnum.values();
        Arrays.stream(values).forEach(alarmTypeEnum -> alarmTypes.put(alarmTypeEnum.getCode(), alarmTypeEnum));
    }

    AlarmTypeEnum(short code) {
        this.code = code;
    }

    public short getCode() {
        return code;
    }

    public static AlarmTypeEnum parseCode(short code) {
        return alarmTypes.get(code);
    }

    public static void main(String[] args) {
        System.out.println(AlarmTypeEnum.parseCode((short) 2));
    }

}

  

原文地址:https://www.cnblogs.com/zhangshiwen/p/9013347.html