0

I made this enum that has string values.

I have enum like this:

enum MyEnum {
    NAME_ONE("one"),
    NAME_TWO("two");

    private String value;

    MyEnum(String value) {
        this.value = value;
    }

    public String toString() {
        return value;
    }
}

Now, I want to convert String into Enum:

String enumValue = "one";
MyEnum mMyEnum = ??? // I want to make MyEnum.NAME_ONE from "one", but how?
Joon. P
  • 2,238
  • 7
  • 26
  • 53

1 Answers1

1

You can add a method to your enum:

public static MyEnum parseValue (final String value) {
    for (final MyEnum me : MyEnum.values()) {
        if (me.value.equals(value)) {
            return me;
        }
    }
    throw new IllegalArgumentException("Incorrect value: " + value);
}

And call it like that:

String enumValue = "one";
MyEnum mMyEnum = MyEnum.parseValue(enumValue);
Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
  • would this be the only way? – Joon. P Dec 06 '16 at 14:16
  • @Joon.P The best way would be to have `enum` values having the same name as the `String` value, and use `valueOf()`, as suggested in the answer linked by @jon-skeet. If it's not possible, you can change the implementation of `parseValue()` to use a `Map`, if you have a lot of enum values and you want better performances. – Florent Bayle Dec 06 '16 at 14:28
  • Thanks! I get it now. – Joon. P Dec 06 '16 at 14:39