开发者

If you have a String and the enum doesn't have a getSomething(String str) method, how do you look up the enum value?

I need to set an enum value like so:

this.myEnum = ThirdPartyEnum.ABC;

But the value I have available to me is not in Enum form.

It's just a raw string:

"ABC"

The ThirdPartyEnum does not have a ThirdPartyEnum.lookupEnumForString().

开发者_C百科

How do I translate the String

"ABC"

to:

ThirdPartyEnum.ABC


You can do

ThirdPartyEnum.valueOf("ABC");

Just to add, and relating to the lookupEnumForString() method you mentioned, if you wanted to search an enumerated value by one of its attributes, you could use values(). Note that values() is public, and you could also use it in case of a third party enum over which you don't have control.

public enum MyEnum {

    VAL1("1"), VAL2("2");

    String attr;
    private MyEnum(String attr){
        this.attr = attr;
    }
    public String getAttr() { return attr; }

    public static MyEnum getByAttr(String searchAttr) {
        for(MyEnum t : values()){
            if(searchAttr.equals(t.getAttr())){
                return t;
            }
        }
    }
}


Try Enum.valueOf()

Enum.valueOf()

Or

ThirdPartyEnum.valueOf("ABC");

valueOf is a default method that is defined for all Java Enum classes.

If you are into functional programming, Guava provides a method for creating a Function to get the valueOf.

Enums.valueOfFunction

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜