使用唯一属性检索枚举值

是否可以创建一个通用方法或类来从给定的唯一属性(带有getter方法的字段)中检索枚举值?

所以你会:

public enum EnumToMap { E1("key1"), E2("key2"), ; private final String key; private EnumToMap(String key) { this.key = key; } public String getKey() { return key; } } 

所以要求的function与之相同

 public static EnumToMap getByKey(String key) ... 

会提供。 优选地,没有reflection并且尽可能通用(但是在这种情况下,可能无法创建没有reflection的通用解决方案)。

澄清:所以这个方法应该适用于多个枚举。 这个想法不是一遍又一遍地实现查找。

实际上只能使用generics和界面。

创建并实现界面

 interface WithKeyEnum { String getKey(); } enum EnumToMap implements WithKeyEnum { ... @Override public String getKey() { return key; } } 

履行

 public static  & WithKeyEnum> T getByKey(Class enumTypeClass, String key) { for (T type : enumTypeClass.getEnumConstants()) { if (type.getKey().equals(key)) { return type; } } throw new IllegalArgumentException(); } 

用法

 EnumToMap instanceOfE1 = getByKey(EnumToMap.class, "key1"); 

如果你想放弃泛化并获得O(1)复杂性,可以使用HashMap来获取它

 public enum EnumToMap{ E1("key1"), E2("key2"); private final String key; private static final Map keys = new HashMap(); static { for (EnumToMap value : values()) { keys.put(value.getKey(), value); } } private EnumToMap(String key) { this.key = key; } public String getKey() { return key; } public static EnumToMap getByKey(String key) { return keys.get(key); } } 

由于必须有一个存储地图的对象 ,因此很难简单化。 Enum本身似乎是很好的候选人。