Reputation: 1804
class Clazz{
public enum MyEnum{
Hello, World
}
}
With class Clazz
, how do I get MyEnum.values()
?
An example of the usage is :
Class unknownClass = getSomeClass();
How to get MyEnum.values()
from unknownClass
?
Upvotes: 4
Views: 2392
Reputation: 339
Method method = parameterIDClass.getMethod("values");
Enum<?>[] enums = (Enum<?>[])method.invoke(null);
Upvotes: 0
Reputation: 22972
You can do Clazz.MyEnum.values()
to access the Enum
or you can directly import MyEnum
in your other classes import com.in.Clazz.MyEnum
becuase MyEnum
is public
.
To get MyEnum
constant via reflection, but if MyEnum
is accessible then there is no need to use reflection. You can do it in following way,
Class<?> clazz = Clazz.class;//You are getting dynamically
Class<?> enumClass = clazz.getDeclaredClasses()[0];//assuming at index 0
Enum<?>[] enumConstants = (Enum<?>[]) enumClass.getEnumConstants();
System.out.println(enumConstants[0]);
OUTPUT
Hello
Upvotes: 6