tags:

views:

95

answers:

3

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)

+2  A: 

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
Manuel Selva
+4  A: 

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
polygenelubricants
I can not use it without access to Alphabet. Say there's Class cls = Alphabet.class and work only with cls.
Joel
@Joel: getting around the generic type check is tricky (I don't think there's a typesafe way of doing it if you start with a `Class<?>`), but I'm not sure what you're saying. This definitely works, but `Class.getEnumConstants()` is best.
polygenelubricants
@polygenelubricants Thanks for your answer. I looked at it, learned from it and marked it useful. As you suggest, I accepted the getEnumConstants() answer. The main reason for it is that it requires nothing other then the Class object itself.
Joel
+5  A: 

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

Ron Tuffin
+1; this is the best answer!
polygenelubricants