Convert String to equivalent Enum value

JavaEnums

Java Problem Overview


Is it possible for me to convert a String to an equivalent value in an Enumeration, using Java.

I can of course do this with a large if-else statement, but I would like to avoid this if possible.

Given this documentation:

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Enumeration.html

I am not too hopeful that this is possible without ifs or a case statement.

Java Solutions


Solution 1 - Java

Hope you realise, java.util.Enumeration is different from the Java 1.5 Enum types.

You can simply use YourEnum.valueOf("String") to get the equivalent enum type.

Thus if your enum is defined as so:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY
}

You could do this:

String day = "SUNDAY";

Day dayEnum = Day.valueOf(day);

Solution 2 - Java

Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration class), you can use the valueOf method of java.lang.Enum subclass:

MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");

Solution 3 - Java

Use static method valueOf(String) defined for each enum.

For example if you have enum MyEnum you can say MyEnum.valueOf("foo")

Solution 4 - Java

I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed.

I guess it gives more granular control but I'm not sure it's really necessary.

public enum Type {
    DEBIT,
    CREDIT;

    public static Map<String, Type> typeMapping = Maps.newHashMap();
    static {
        typeMapping.put(DEBIT.name(), DEBIT);
        typeMapping.put(CREDIT.name(), CREDIT);
    }

    public static Type getType(String typeName) {
        if (typeMapping.get(typeName) == null) {
            throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
        }
        return typeMapping.get(typeName);
    }
}

I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnkurView Question on Stackoverflow
Solution 1 - JavaadarshrView Answer on Stackoverflow
Solution 2 - JavaXionView Answer on Stackoverflow
Solution 3 - JavaAlexRView Answer on Stackoverflow
Solution 4 - JavafIwJlxSzApHEZIlView Answer on Stackoverflow