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

Community
  • 1
  • 1
James MV
  • 8,381
  • 16
  • 63
  • 92

7 Answers7

10

Use AnotherClass.MyEnum.valueOf(toPass)

red1ynx
  • 3,506
  • 1
  • 17
  • 22
9

Do you mean like ...

MyEnum e = MyEnum.valueOf(text);

or

MyEnum e = Enum.valueOf(MyEnum.class, text);
Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106
2

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

Michael Borgwardt
  • 335,521
  • 76
  • 467
  • 706
2

Try doing this in the body of method:

AnotherClass.toPass.PassedEnum.valueOf(toPass);
Chris
  • 22,440
  • 4
  • 55
  • 49
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.

Barend
  • 17,040
  • 2
  • 56
  • 80
2
public static void method(String toPass){

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

}
Surasin Tancharoen
  • 4,790
  • 4
  • 31
  • 35
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);
}
x4u
  • 13,537
  • 5
  • 47
  • 57