0

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().

How do I translate the String

"ABC"

to:

ThirdPartyEnum.ABC

2 Answers2

4

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;
            }
        }
    }
}
Xavi López
  • 27,550
  • 11
  • 97
  • 161
2

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

John B
  • 32,493
  • 6
  • 77
  • 98