Java Enum getDeclaringClass vs getClass

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.

Leave a Comment