michelemarcon
michelemarcon

Reputation: 24767

Java create an instance of enum via reflection

I want to get an instance to an enum type, so that:

String enumString="abc";
MyClass.MyEnum enumType=Class.forName("com.MyClass.MyEnum."+enumString);

This gives me an inconvertible types.

Upvotes: 7

Views: 15961

Answers (3)

ataylor
ataylor

Reputation: 66069

Enum.valueOf will do it, but it is pretty picky about it's type. Make sure you cast the Class to Class<? extends Enum>. Example:

enum Foo {
    BLAT,
    BLARG
};

System.out.println(Enum.valueOf((Class<? extends Enum>)Class.forName("Foo"), "BLARG"));

Upvotes: 24

Andy Thomas
Andy Thomas

Reputation: 86411

Have a look at Enum.valueOf( Class enumType, String name ).

Upvotes: 10

Yishai
Yishai

Reputation: 91881

You are looking for MyClass.MyEnum.valueOf(enumString). No need to fully qualify the class in the string.

Upvotes: 8

Related Questions