java8 枚举_java8下 枚举 通用方法

在项目中经常用到枚举作为数据字典值和描述的相互转化。

用法如下:

public enum CommunicationParamsCom {

COM_1(1, "COM1"), COM_2(2, "485端口1"), COM_3(3, "485端口2"), COM_31(31, "载波");

private int value;

private String key;

CommunicationParamsCom(int value, String key) {

this.value = value;

this.key = key;

}

public int getValue() {

return value;

}

public String getKey() {

return key;

}

public static CommunicationParamsCom getEnmuByValue(int value) {

for (CommunicationParamsCom item : values()) {

if (value == item.getValue()) {

return item;

}

}

return null;

}

public static CommunicationParamsCom getEnmuByKey(String key) {

if (StringUtil.isEmpty(key)) {

return null;

}

for (CommunicationParamsCom item : values()) {

if (key.equals(item.getKey())) {

return item;

}

}

return null;

}

}

当枚举类多了之后,会存在很多重复的值和描述相互转化的方法,类似getEnmuByValue和getEnmuByKey。

最近找到一种方法,利用接口、接口默认方法、泛型,实现通用的方法。同类型的枚举只需要实现该接口即可。

代码如下:

1 public interfaceICommonEnum {2 intgetValue();3

4 String getKey();5

6 static & ICommonEnum> E getEnmu(Integer value, Classclazz) {7 Objects.requireNonNull(value);8 EnumSet all =EnumSet.allOf(clazz);9 return all.stream().filter(e -> e.getValue() == value).findFirst().orElse(null);10 }11

12 static & ICommonEnum> E getEnmu(String key, Classclazz) {13 Objects.requireNonNull(key);14 EnumSet all =EnumSet.allOf(clazz);15 return all.stream().filter(e -> e.getKey().equals(key)).findFirst().orElse(null);16 }17 }

具体用法:

1 public enum RtuProtocol implementsICommonEnum {2 PTL_A(1, "A规约"), PTL_B(2, "B规约");3

4 private intvalue;5 privateString key;6

7 RtuProtocol(intvalue, String key) {8 this.value =value;9 this.key =key;10 }11

12 public intgetValue() {13 returnvalue;14 }15

16 publicString getKey() {17 returnkey;18 }19 }

转换时的调用举例:

RtuProtocol = ICommonEnum.getEnmu(1,RtuProtocol.class)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值