Reputation: 24464
If I want IDE to show an error from annotation processing on the annotation itself, I should use the following form of printMessage():
printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a)
But I cannot find a nice and simple way to get that AnnotationMirror.
Using code samples, these and these, combining what I found there, I had found a complicated way:
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Set<? extends Element> classesForBuilder = roundEnv.getElementsAnnotatedWith(AddBuilder.class);
for(Element classElement : classesForBuilder){
if (classElement.getModifiers().contains(Modifier.ABSTRACT)) {
return annoError(classElement, "AnnoBuilder cannot be applied to an abstract class.", AddBuilder.class);
.......
boolean annoError(Element annotatedElement, String message, Class<? extends Annotation> annoClass ){
for(AnnotationMirror annotationMirror : annotatedElement.getAnnotationMirrors()){
>>>>>>>>if(((TypeElement)annotationMirror.getAnnotationType().asElement())
.getQualifiedName().toString()
.equals( annoClass.getCanonicalName())) {
messager.printMessage(Kind.ERROR, message, annotatedElement, annotationMirror);
} else {
messager.printMessage(Kind.ERROR, message+" + no Annotation found.", annotatedElement);
}
}
return true;
}
That works. But I do not like the really terrible second if
.
I had found a shorter way of comparison through String:
if(annotationMirror.getAnnotationType().toString().equals(annoClass.getCanonicalName()))
I do not understand why only that super-long way of comparison through many classes is used in all published examples.
But still I would like to have it shorter.
if(annotationMirror.getAnnotationType().equals(annoClass))
does not work.
Can I compare classes somehow without turning them into names?
Upvotes: 1
Views: 150
Reputation: 1054
I think what you are asking for present in the Types
class and you can use the isSameType
method like this
annotatedElement.getAnnotationMirrors()
.stream()
.filter(annotationMirror -> types.isSameType(annotationMirror.getAnnotationType(), elements.getTypeElement(annoClass.getCanonicalName()).asType()))
.findFirst()
.map(annotationMirror -> {
messager.printMessage(Diagnostic.Kind.ERROR, message, annotatedElement, annotationMirror);
return true;
})
.orElseGet(() -> {
messager.printMessage(Diagnostic.Kind.ERROR, message + " + no Annotation found.", annotatedElement);
return false;
});
And you should not use Strings literals obtained from types names for comparison like this as it might work differently between intellij and eclipse.
Upvotes: 1