IsEnum () ambiguous behavior for anonymous inner class

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.

+4
source share
2 answers

If my understanding is correct, Class#isEnum()it is not intended to test whether a class is an enumeration. It just allows you to intrigue a class declaration.

As mentioned in the comment, what you want to do is easily achievable

yourEnumValue.getClass().isAssignableFrom(Enum.class)

or

yourEnumValue instanceof Enum
+3
source

, enumWorkaround, , . isEnum:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/lang/Class.java#Class.isEnum%28%29

enum . , enumWorkaround - , hava , java.lang.Enum, , ...

+1

Source: https://habr.com/ru/post/1622681/


All Articles