15

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

1
  • Thanks to all just what was needed. Commented Nov 21, 2011 at 14:43

7 Answers 7

10

Use AnotherClass.MyEnum.valueOf(toPass)

Sign up to request clarification or add additional context in comments.

Comments

9

Do you mean like ...

MyEnum e = MyEnum.valueOf(text);

or

MyEnum e = Enum.valueOf(MyEnum.class, text);

Comments

2

I think the static factory method Enum.valueOf() does what you want.

Comments

2

Try doing this in the body of method:

AnotherClass.toPass.PassedEnum.valueOf(toPass);

Comments

2

You can use Enum.valueOf(Class<...>, String) to convert a string to the corresponding enum instance:

MyEnum value = Enum.valueOf(MyEnum.class, "ENUM_VALUE");

If the string contains a value that does not exist as an enum constant, this method throws IllegalArgumentException.

Comments

2
public static void method(String toPass){

 mymethod(AnotherClass.MyEnum.valueOf(toPass));

}

Comments

2

You can use the static method Enum.valueOf to convert a string to a Enum value:

public static void method(String toPass)
{
    AnotherClass.MyEnum eval = Enum.valueOf(AnotherClass.MyEnum.class,toPass);
    mymethod(eval);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.