Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing values of unknown enum

Tags:

java

enums

class

Say we have a Class object. Name it cls.

Now cls.isEnum() returns true

What a joy!!! Could I please have the values listed to me? (one sugar, no milk)

like image 403
Joel Shemtov Avatar asked Aug 03 '10 10:08

Joel Shemtov


3 Answers

getEnumConstants() a method of the Class object returns an array of Objects

public static enum E {
    A, B, C, D;
}

public static void main(String[] args) {
    Class c = E.class;
    for(Object b:c.getEnumConstants())
    {
        System.out.println(b);
    }
}

Prints:

A
B
C
D

like image 172
Ron Tuffin Avatar answered Nov 14 '22 10:11

Ron Tuffin


You can use EnumSet.allOf(Class<E>), where <E extends Enum<E>>

Given:

public static enum Alphabet {
    A, B, C, D;
}

You can write:

    for (Enum<?> e : EnumSet.allOf(Alphabet.class)) {
        System.out.println(e);
    }
    // A, B, C, D
like image 26
polygenelubricants Avatar answered Nov 14 '22 08:11

polygenelubricants


The following main:

public class GetEnumFields {

public static enum Enum {

    A, B, C, D;
}

public static void main(String[] args) {

    Enum a = Enum.A;
    Field[] declaredFields = a.getClass().getDeclaredFields();
    for (int i = 0; i < declaredFields.length; i++) {
        System.out.println(declaredFields[i]);
    }
}

}

prints:

public static final GetEnumFields$Enum GetEnumFields$Enum.A
public static final GetEnumFields$Enum GetEnumFields$Enum.B
public static final GetEnumFields$Enum GetEnumFields$Enum.C
public static final GetEnumFields$Enum GetEnumFields$Enum.D
private static final GetEnumFields$Enum[] GetEnumFields$Enum.ENUM$VALUES
like image 2
Manuel Selva Avatar answered Nov 14 '22 10:11

Manuel Selva