当前位置: 移动技术网 > IT编程>开发语言>Java > java8下 枚举 通用方法

java8下 枚举 通用方法

2019年12月26日  | 移动技术网IT编程  | 我要评论
在项目中经常用到枚举作为数据字典值和描述的相互转化。 用法如下: 当枚举类多了之后,会存在很多重复的值和描述相互转化的方法,类似getEnmuByValue和getEnmuByKey。 最近找到一种方法,利用接口、接口默认方法、泛型,实现通用的方法。同类型的枚举只需要实现该接口即可。 代码如下: 具 ...

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

用法如下:

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 = icommonenum.getenmu(1,rtuprotocol.class)



如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网