Java Enum getDeclaringClass vs getClass

The docs for the Java Enum class state the following about getDeclaringClass:

Returns the Class object corresponding to this enum constant's enum type. Two enum constants e1 and e2 are of the same enum type if and only if e1.getDeclaringClass() == e2.getDeclaringClass(). (The value returned by this method may differ from the one returned by the Object.getClass() method for enum constants with constant-specific class bodies.)

I don't understand when getClass and getDeclaringClass are different. Can someone provide an example along with an explanation?


Solution 1:

Java enum values are permitted to have value-specific class bodies, e.g. (and I hope this syntax is correct...)

public enum MyEnum {

   A {
       void doSomething() { ... }
   },


   B {
       void doSomethingElse() { ... }
   };
}

This will generate inner classes representing the class bodies for A and B. These inner classes will be subclasses of MyEnum.

MyEnum.A.getClass() will return the anonymous class representing A's class body, which may not be what you want.

MyEnum.A.getDeclaringClass(), on the other hand, will return the Class object representing MyEnum.

For simple enums (i.e. ones without constant-specific class bodies), getClass() and getDeclaringClass() return the same thing.