使用唯一属性检索枚举值

Maa*_*wes 1 java enums map

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

所以你会:

public enum EnumToMap {
    E1("key1"),
    E2("key2"),
    ;

    private final String key;

    private EnumToMap(String key) {
        this.key = key;
    }

    public String getKey() {
        return key;
    }
}
Run Code Online (Sandbox Code Playgroud)

所需要的功能与

public static EnumToMap getByKey(String key)
    ...
Run Code Online (Sandbox Code Playgroud)

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

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

dam*_*nix 5

实际上只能使用泛型和界面.

创建并实现界面

interface WithKeyEnum {
    String getKey();
}

enum EnumToMap implements WithKeyEnum {
    ...

    @Override
    public String getKey() {
        return key;
    }
}
Run Code Online (Sandbox Code Playgroud)

履行

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();
}
Run Code Online (Sandbox Code Playgroud)

用法

EnumToMap instanceOfE1 = getByKey(EnumToMap.class, "key1");
Run Code Online (Sandbox Code Playgroud)

  • 使用界面比使用反射更好;) (2认同)