In my understanding, it Class.isEnum()should return true for any value of the enumeration declared using the instruction enum.
If an enumeration is declared anonymously, it returns false.
The documentation for isEnum()indicates the following:
"Returns true if and only if this class has been declared as an enumeration in the source code.
It seems to me a little ambiguous.
I'm looking for a way to distinguish enumeration constants from other objects, so I need isEnum()to return true for all enumeration constants, even if they anonymously override something.
Is there a way to identify enumeration constants besides this?
Run the class and look at the results isEnum()for each constant. It will print a value isEnum()for each constant.
I expected all constants to return to value isEnum(). But, unfortunately, the third constant returns false for isEnum().
public enum EnumTest {
Alpha(3), Beta(6), Delta(4) {
@Override
public int getValue() {
return -1;
}
@Override
public String toString() {
return "Gamma";
}
},
Epsilon(9);
private int value;
EnumTest(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public static boolean isEnumWorkaround(Class enumClass) {
while (enumClass.isAnonymousClass()) {
enumClass = enumClass.getSuperclass();
}
return enumClass.isEnum();
}
public static void main(String[] args) {
for (EnumTest thing : EnumTest.values()) {
String nameString = thing + " (" + thing.name() + ")";
System.out.println(String.format(
"%-18s isEnum = %-5b [workaround isEnum = %b]", nameString, thing
.getClass().isEnum(), isEnumWorkaround(thing.getClass())));
}
}
}
Please check and let me know if I understand correctly or not.
source
share