Java creates an enum instance through reflection

I want to get an instance of an enumeration type so that:

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

This gives me irreversible types.

+4
source share
3 answers

You are looking for MyClass.MyEnum.valueOf(enumString) . It is not necessary to fully qualify a class in a string.

+7
source

Enum.valueOf will do this, but it is pretty legible in this type. Make sure you drop Class on Class<? extends Enum> Class<? extends Enum> . Example:

 enum Foo { BLAT, BLARG }; System.out.println(Enum.valueOf((Class<? extends Enum>)Class.forName("Foo"), "BLARG")); 
+15
source

Source: https://habr.com/ru/post/1341179/


All Articles