使用独特属性检索枚举值 [英] Retrieve enum value using unique property

查看:180
本文介绍了使用独特属性检索枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个通用的方法或类来从给定的唯一属性(带有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)
...


。最好没有反射和尽可能的通用(但在这种情况下,可能无法创建一个通用的解决方案而不反思)。



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

解决方案

实际上可能只是用泛型和接口。 p>

创建和实现界面

  interface WithKeyEnum {
String getKey();
}

枚举EnumToMap实现WithKeyEnum {
...

@Override
public String getKey(){
return键;
}
}

实施

  public static< T extends Enum< T> &安培; WithKeyEnum> T getByKey(Class< T> enumTypeClass,String key){
for(T type:enumTypeClass.getEnumConstants()){
if(type.getKey()。equals(key)){
返回类型;
}
}
throw new IllegalArgumentException();
}

使用

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


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.

解决方案

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");

这篇关于使用独特属性检索枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆