Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Enum? [duplicate]

Tags:

java

Possible Duplicate:
Java - Convert String to enum

I have a method that uses an enum:

mymethod(AnotherClass.MyEnum.PassedEnum);

And I want to nest this within a class that receives a String which becomes MyEnum:

public static void method(String toPass){

 mymethod(AnotherClass.toPass.PassedEnum);

}

The passed variable has to be a String but I need to convert it to a Enum to pass to AnotherClass?

TIA

like image 389
James MV Avatar asked Nov 21 '11 14:11

James MV


People also ask

How do I convert string to enum?

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.

Can we assign string to enum?

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.

Is enum TryParse case sensitive?

The case-sensitive string representation of the enumeration name or underlying value to convert. When this method returns, contains an object of type TEnum whose value is represented by value if the parse operation succeeds.


2 Answers

Use AnotherClass.MyEnum.valueOf(toPass)

like image 109
red1ynx Avatar answered Sep 28 '22 07:09

red1ynx


Do you mean like ...

MyEnum e = MyEnum.valueOf(text);

or

MyEnum e = Enum.valueOf(MyEnum.class, text);
like image 40
Peter Lawrey Avatar answered Sep 28 '22 07:09

Peter Lawrey