Convert String to equivalent Enum value

Ankur picture Ankur · Aug 14, 2011 · Viewed 129k times · Source

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.

Answer

adarshr picture adarshr · Aug 14, 2011

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