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.
You can create Enum from String by using Enum. valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods.
To convert string to enum use static method Enum. Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.
The valueOf() method of the Enum class in java accepts a String value and returns an enum constant of the specified type.
The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With