Get annotations for enum type variable

前端 未结 5 964
孤城傲影
孤城傲影 2020-12-29 02:34

I have some nonnull variable (e.g. en1) of Enum type. The question is: how to get annotations related to enumeration constant referenced by e

5条回答
  •  执念已碎
    2020-12-29 02:54

    If you are using an obfuscator such as Proguard, you might find that the enum fields have been renamed, while .name() still returns the original name of the field. For example, this enum...

    enum En {
        FOO,
        BAR
    }
    

    ...would become this after ProGuarding...

    enum En {
        a,
        b
    }
    

    ...but En.FOO.name() will still return "FOO", causing getField(En.FOO.name()) to fail because it expects the field to be named "a".

    If you want to get the Field for a specific enum field from obfuscated code, you can do this:

    for (Field field : En.class.getDeclaredFields()) {
        if (field.isEnumConstant()) {
            try {
                if (en1 == field.get(null)) {
                    Annotation[] annotations = field.getAnnotations();
                }
            } catch (IllegalAccessException e) {
                // 
            }
        }
    }
    

提交回复
热议问题