Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 875
michelemarcon Avatar asked Feb 24 '11 17:02

michelemarcon


2 Answers

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"));
like image 69
ataylor Avatar answered Oct 11 '22 00:10

ataylor


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

like image 33
Andy Thomas Avatar answered Oct 10 '22 23:10

Andy Thomas