问题
Is it possible to create a generic method or class to retrieve an enum value from a given unique property (field with getter method)?
So you would have:
public enum EnumToMap {
E1("key1"),
E2("key2"),
;
private final String key;
private EnumToMap(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
so required is the same functionality as
public static EnumToMap getByKey(String key)
...
would provide. Preferably without reflection and as generic as possible (but in this case it may not be possible to create a generic solution without reflection).
Clarification: So this method should work for multiple enumerations. The idea is not to have to implement the lookup over and over again.
回答1:
Actually possible just with generics and interface.
Create and implement interface
interface WithKeyEnum {
String getKey();
}
enum EnumToMap implements WithKeyEnum {
...
@Override
public String getKey() {
return key;
}
}
Implementation
public static <T extends Enum<T> & WithKeyEnum> T getByKey(Class<T> enumTypeClass, String key) {
for (T type : enumTypeClass.getEnumConstants()) {
if (type.getKey().equals(key)) {
return type;
}
}
throw new IllegalArgumentException();
}
Usage
EnumToMap instanceOfE1 = getByKey(EnumToMap.class, "key1");
回答2:
If you want to drop generification and get O(1) complexity use HashMap
to get it
public enum EnumToMap{
E1("key1"),
E2("key2");
private final String key;
private static final Map<String, EnumToMap> keys = new HashMap<String, EnumToMap>();
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);
}
}
This would be hard to just generify as there must be an object to store the map. Enum itself seems to be good candidate for that.
来源:https://stackoverflow.com/questions/26170107/retrieve-enum-value-using-unique-property