Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isEnum() does not recognise java.lang.Enum

Tags:

java

enums

isEnum() is working absolutely fine for enum defined in java class .

To my surprise it if failing for java.lang.Enum.class.isEnum().

Following code produces true, false as output, however I am expecting true, true

public class Test {
        public static void main(String[] args) {
            System.out.println(Color.class.isEnum());
            System.out.println(java.lang.Enum.class.isEnum());
        }
    }

    enum Color {
        RED, GREEN, BLUE;
    }

Why is isEnum() behaving like this ?

like image 915
Sachin Sachdeva Avatar asked Dec 03 '22 17:12

Sachin Sachdeva


2 Answers

You can easily see in Enum source code that java.lang.Enum is actually a class:

public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable {
//...
}
like image 174
Tasos P. Avatar answered Dec 08 '22 00:12

Tasos P.


The docs of isEnum() state:

Returns true if and only if this class was declared as an enum in the source code.

java.lang.Enum is declared as

public abstract class Enum<E extends Enum<E>>...

So, by definition, it's not an enum. Beside this, the implementation of isEnum() also gives another hint:

public boolean isEnum() {
    // An enum must both directly extend java.lang.Enum and have
    // the ENUM bit set; classes for specialized enum constants
    // don't do the former.
    return (this.getModifiers() & ENUM) != 0 &&
    this.getSuperclass() == java.lang.Enum.class;
}

java.lang.Enum.class wouldn't pass the last check

like image 24
ernest_k Avatar answered Dec 08 '22 01:12

ernest_k