Getting the Constants of an Enumeration

suggest change

Giving this enumeration as Example:

enum Compass {
    NORTH(0),
    EAST(90),
    SOUTH(180),
    WEST(270);
    private int degree;
    Compass(int deg){
        degree = deg;
    }
    public int getDegree(){
        return degree;
    }
}

In Java an enum class is like any other class but has some definied constants for the enum values. Additionally it has a field that is an array that holds all the values and two static methods with name values() and valueOf(String). We can see this if we use Reflection to print all fields in this class

for(Field f : Compass.class.getDeclaredFields())
    System.out.println(f.getName());

the output will be:

NORTHEASTSOUTHWESTdegreeENUM$VALUES

So we could examine enum classes with Reflection like any other class. But the Reflection API offers three enum-specific methods.

enum check

Compass.class.isEnum();

Returns true for classes that represents an enum type.

retrieving values

Object[] values = Compass.class.getEnumConstants();

Returns an array of all enum values like Compass.values() but without the need of an instance.

enum constant check

for(Field f : Compass.class.getDeclaredFields()){
    if(f.isEnumConstant())
        System.out.println(f.getName());
}

Lists all the class fields that are enum values.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Reflection API:
* Getting the Constants of an Enumeration

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
44 Reflection API
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap