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)
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)
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
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
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