Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Element Annotation from an AnnotationMirror

Is there an better way to get an Element Annotation from an AnnotationMirror than this? This seems really hacky 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();
    }
}
like image 255
Michael Pardo Avatar asked Apr 25 '14 18:04

Michael Pardo


2 Answers

I think you just want:

javax.lang.model.element.Element

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

Returns this element's annotation for the specified type if such an annotation is present, else null. The annotation may be either inherited or directly present on this element.

And supply a class explicitly (e.g., name.class).

It is hard to see why you would want to use Class.forName(variable) instead of name.class to explicitly name the class. If you use the forName call you don't actually know the type of annotation you are getting. You would have to follow it by an instanceof or something similar to check what annotation you had got, in which case you might as well have just explicitly requested that annotation type.

like image 94
rghome Avatar answered Sep 28 '22 06:09

rghome


The short answer is: it can't be done -- you have to use Class.forName().

The javax.lang.model package (and subpackages) are designed for dealing with source code (the primary use case being annotation processors). In these cases, you typically have not yet produced binary artifacts (i.e. .class files) for the Elements you're dealing with, so invoking Class.forName() is likely to fail.

If you can give us more details about where element comes from or what you want to do with annotation once you've obtained it, we might be able to provide more guidance. It's likely that the DeclaredType returned by annotationMirror.getAnnotationType() provides access to the information you're after in a more reliable way than Annotation would.

like image 40
Matt McHenry Avatar answered Sep 28 '22 06:09

Matt McHenry