最近常常有一些项目需要给枚举设值一个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));
}
}