是否可以创建一个通用方法或类来从给定的唯一属性(具有 getter 方法的字段)中检索枚举值?
所以你会:
public enum EnumToMap {
E1("key1"),
E2("key2"),
;
private final String key;
private EnumToMap(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
所以需要的是与
相同的功能public static EnumToMap getByKey(String key)
...
会提供。最好没有反射并尽可能通用(但在这种情况下,可能无法创建没有反射的通用解决方案)。
澄清:所以这个方法应该适用于多个枚举。这个想法是不必一遍又一遍地实现查找。
最佳答案
实际上只需要泛型和接口(interface)就可以实现。
创建并实现接口(interface)
interface WithKeyEnum {
String getKey();
}
enum EnumToMap implements WithKeyEnum {
...
@Override
public String getKey() {
return key;
}
}
实现
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();
}
用法
EnumToMap instanceOfE1 = getByKey(EnumToMap.class, "key1");
关于java - 使用唯一属性检索枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26170107/