Convert String to equivalent Enum value

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

I can, of course, do this with the big if-else , but I would like to avoid this if possible.

Based on this documentation:

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

I do not really hope that this is possible without ifs or case case.

+48
java enums
Aug 14 2018-11-11T00:
source share
4 answers

I hope you understand java.util.Enumeration is different from the Java 1.5 Enum types.

You can simply use YourEnum.valueOf("String") to get an equivalent enumeration type.

Thus, if your listing is defined like this:

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

You can do it:

 String day = "SUNDAY"; Day dayEnum = Day.valueOf(day); 
+115
Aug 14 '11 at 13:10
source share

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

 MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS"); 
+11
Aug 14 '11 at 13:10
source share

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

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

+4
Aug 14 '11 at 13:10
source share

I could rework my own solution without realizing that Type.valueOf("enum string") really exists.

I think this gives more detailed control, but I'm not sure if this is 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 assume that you are exchanging IllegalArgumentException for a RuntimeException (or any other exception you want to throw) that could potentially clear the code.

0
Jun 14 '17 at 22:56 on
source share



All Articles