Java

Java

By DeepSource

getClass should not be used with enums whose members have custom bodies JAVA-E1106

Bug risk
Major
Autofix

Enum 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";
        }
    };
}

Bad Practice

MyEnum value = MyEnum.VARIANT_THREE;

Class<MyEnum> clazz = value.getClass(); // returns MyEnum$1.class

Recommended

Use the getDeclaringClass() method instead.

Class<MyEnum> clazz = value.getDeclaringClass(); // returns MyEnum.class correctly.