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

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

1 public enumMatchResultEnum {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 intcode;20

21 MatchResultEnum(intvalue) {22 this.code =value;23 }24

25 public intgetCode() {26 returncode;27 }28

29

30 public static MatchResultEnum parse(intvalue) {31 MatchResultEnum[] values =values();32 for(MatchResultEnum matchResult : values) {33 if (matchResult.code ==value) {34 returnmatchResult;35 }36 }37 return null;38 }39 }

后期优化如下:

1 private static MatchResultEnum[] result ={WIN, LOSE, DRAW};2 public static MatchResultEnum parse(intvalue) {3 if (value

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 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));

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值