4
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?

akash
  • 22,664
  • 11
  • 59
  • 87
theAnonymous
  • 1,701
  • 2
  • 28
  • 62

2 Answers2

6

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
akash
  • 22,664
  • 11
  • 59
  • 87
0

The answer is here:

Method method = parameterIDClass.getMethod("values");
Enum<?>[] enums = (Enum<?>[])method.invoke(null);