views:

241

answers:

1

I have a simple key-value property file where I need to parse a value which is then to be assigned to an enum type. What is the best way to do this?

The only thing that comes up to my mind is something like iterating through all the possible values of the enums.toString and see if it equals any of them.

+6  A: 

Enum.valueOf (or rather, its wrapper which is synthesized in and for every enum class) does what you want.

enum Color { RED, GREEN, BLUE }

// somewhere in your code
String colorName = "GREEN";
try {
    Color color = Color.valueOf(colorName);
} catch (IllegalArgumentException e){
    // colorName was not the name of a member of the enum
}
gustafc
Ah, how stupid I was. I was looking for valueOf in the java Enum class, but not my particular one.
pg-robban