Get annotations for enum type variable

前端 未结 5 979
孤城傲影
孤城傲影 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:51

    Further to the existing answers, if you are in control of the enum class (can edit it), you could simply add a method to the enum to fetch the required annotation i.e.

    AnnotationClass getAnnotation(){
       Field field = this.getClass().getField(this.name());
       return field.getAnnotation(AnnotationClass.class);       
    }
    

    or all it's annotations:

    Annotation[] getAnnotations(){
       Field field = this.getClass().getField(this.name());
       return field.getAnnotations();
    }
    

    Adjust the code above to handle exceptions (NoSuchFieldException and SecurityException).

提交回复
热议问题