• 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 interface ICommonEnum {
     2     int getValue();
     3 
     4     String getKey();
     5 
     6     static <E extends Enum<E> & ICommonEnum> E getEnmu(Integer value, Class<E> clazz) {
     7         Objects.requireNonNull(value);
     8         EnumSet<E> all = EnumSet.allOf(clazz);
     9         return all.stream().filter(e -> e.getValue() == value).findFirst().orElse(null);
    10     }
    11 
    12     static <E extends Enum<E> & ICommonEnum> E getEnmu(String key, Class<E> clazz) {
    13         Objects.requireNonNull(key);
    14         EnumSet<E> all = EnumSet.allOf(clazz);
    15         return all.stream().filter(e -> e.getKey().equals(key)).findFirst().orElse(null);
    16     }
    17 }

    具体用法:

     1     public enum RtuProtocol implements ICommonEnum {
     2         PTL_A(1, "A规约"), PTL_B(2, "B规约");
     3 
     4         private int value;
     5         private String key;
     6 
     7         RtuProtocol(int value, String key) {
     8             this.value = value;
     9             this.key = key;
    10         }
    11 
    12         public int getValue() {
    13             return value;
    14         }
    15 
    16         public String getKey() {
    17             return key;
    18         }
    19     }

    转换时的调用举例:

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



  • 相关阅读:
    wordpress取文章时间
    一个链接引发的血案---------服务器 IO及网络流量暴涨解决历程
    wordpres 自定义comment样式
    HTML中head里的内容经浏览器解析后全到body里了
    mir9-lua——《热血沙城》45度ARPG手游-Lua移植版
    MoonWarriors-lua——《雷电战机》游戏-Lua移植版
    《QQ欢乐斗地主》山寨版
    最好的ie版本检测方式
    css 超出部分显示省略号
    分享一个jquery插件,弥补一下hover事件的小小不足
  • 原文地址:https://www.cnblogs.com/legend_sun/p/12098981.html
Copyright © 2020-2023  润新知