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;
    }
}

An enum type is a class with a fixed set of constants. The compiler also adds values() and valueOf(String), and a synthetic array that holds the constants. getDeclaredFields prints each name on its own line. javac calls that array $VALUES. Another compiler may use a different synthetic name, and the language does not fix the order:

for (Field f : Compass.class.getDeclaredFields())
    System.out.println(f.getName());
NORTH
EAST
SOUTH
WEST
degree
$VALUES

Enum types can be examined like other classes. The reflection API also has three enum-specific operations.

enum check

Compass.class.isEnum();

Returns true when the Class object represents an enum type. The anonymous class generated for a constant-specific body returns false.

retrieving values

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

Returns the constants, as Compass.values() does. Both are available without an instance. getEnumConstants() is the one you can call when you only have a Class. It returns null if the class is not an enum. values() returns a new array on every call.

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