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)




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM