Retrieve enum value using unique property

不羁岁月 提交于 2020-02-02 14:45:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!