Close

Java Reflection - How to get all values of an enum via reflection?

Java Reflection Java 

The $VALUES field is implicitly added by the compiler in an enum class. It contains an array of all values of the enum which is normally returned via values() method. This can be used to get all values of enum constant via reflection.

The same values can be obtained by calling values() method reflectively.

package com.logicbig.example.field;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;

public class IsEnumConstantExample4 {

public static void main(String... args) throws Exception {
MyEnum[] values = getEnumValues(MyEnum.class);
System.out.println(Arrays.toString(values));

//alternatively
Method method = MyEnum.class.getDeclaredMethod("values");
Object obj = method.invoke(null);
System.out.println(Arrays.toString((Object[]) obj));
}

private static <E extends Enum> E[] getEnumValues(Class<E> enumClass)
throws NoSuchFieldException, IllegalAccessException {
Field f = enumClass.getDeclaredField("$VALUES");
System.out.println(f);
System.out.println(Modifier.toString(f.getModifiers()));
f.setAccessible(true);
Object o = f.get(null);
return (E[]) o;
}

private static enum MyEnum {
A, B, C
}
}

Output

private static final com.logicbig.example.field.IsEnumConstantExample4$MyEnum[] com.logicbig.example.field.IsEnumConstantExample4$MyEnum.$VALUES
private static final
[A, B, C]
[A, B, C]




See Also