Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to equivalent Enum value

Tags:

java

enums

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.

like image 297
Ankur Avatar asked Aug 14 '11 13:08

Ankur


People also ask

How do you create an enum from a string?

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.

How do you convert a string value to a specific enum type in C #?

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.

Can we convert string to enum in Java?

The valueOf() method of the Enum class in java accepts a String value and returns an enum constant of the specified type.

What is enum parse in C#?

The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.


1 Answers

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); 
like image 153
adarshr Avatar answered Sep 29 '22 14:09

adarshr