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,569
  • 17
  • 65
  • 96

7 Answers7

10

Use AnotherClass.MyEnum.valueOf(toPass)

red1ynx
  • 3,639
  • 1
  • 18
  • 23
9

Do you mean like ...

MyEnum e = MyEnum.valueOf(text);

or

MyEnum e = Enum.valueOf(MyEnum.class, text);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

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

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
2

Try doing this in the body of method:

AnotherClass.toPass.PassedEnum.valueOf(toPass);
Chris
  • 22,923
  • 4
  • 56
  • 50
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,296
  • 2
  • 61
  • 80
2
public static void method(String toPass){

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

}
Surasin Tancharoen
  • 5,520
  • 4
  • 32
  • 40
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,877
  • 6
  • 48
  • 58