Getting annotation of an element from annotation

Is there a better way to get an annotation of an element from AnnotationMirror than this? It seems really uncomfortable to me.

for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
    try {
        Class annotationClass = Class.forName(annotationMirror.getAnnotationType().toString());
        Annotation annotation = element.getAnnotation(annotationClass);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}
+4
source share
2 answers

I think you just want to:

javax.lang.model.element.Element

<A extends Annotation> A getAnnotation(Class<A> annotationType)

Returns this annotation of an element for the specified type, if such an annotation is present, otherwise null. Annotations can be either inherited or directly present in this element.

And enter the class explicitly (e.g. name.class).

, Class.forName(variable) name.class . forName, , . instanceof - , , , .

+1

: - ​​ Class.forName().

javax.lang.model ( ) ( ). , , (.. .class ) Element, , Class.forName(), , .

, Element annotation , , . , DeclaredType, annotationMirror.getAnnotationType(), , , annotation.

+1

Source: https://habr.com/ru/post/1538117/


All Articles