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.
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);
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.
Use static method valueOf(String)
defined for each enum
.
For example if you have enum MyEnum
you can say MyEnum.valueOf("foo")
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");
Source: Stackoverflow.com