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:



Table Of Contents