getClass
should not be used with enums whose members have custom bodies JAVA-E1106Enum variants with custom bodies are implemented as anonymous classes, and calling getClass
on an enum variant with a body will return the Class instance corresponding to the anonymous class, not the enum itself.
Use the getDeclaringClass()
method to retrieve the actual enum type in such cases.
Consider the following example of an enum:
enum MyEnum {
VARIANT_ONE,
VARIANT_TWO,
// This declares an anonymous subclass of MyEnum!
VARIANT_THREE {
@Override
public String toString() {
return "This is variant three";
}
};
}
MyEnum value = MyEnum.VARIANT_THREE;
Class<MyEnum> clazz = value.getClass(); // returns MyEnum$1.class
Use the getDeclaringClass()
method instead.
Class<MyEnum> clazz = value.getDeclaringClass(); // returns MyEnum.class correctly.