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)
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With