首页 > 解决方案 > 我可以在短时间内找到合适的 MirrorAnnotation 吗?

问题描述

如果我希望 IDE 显示注释本身的注释处理错误,我应该使用以下形式的 printMessage():

printMessage​(Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a)

但是我找不到一个简单的方法来获取 AnnotationMirror。

使用代码示例,这些这些,结合我在那里找到的内容,我发现了一个复杂的方法:

@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;
}

这样可行。但我不喜欢真正可怕的第二个if

我通过String找到了一种更短的比较方法:

if(annotationMirror.getAnnotationType().toString().equals(annoClass.getCanonicalName())) 

我不明白为什么在所有已发布的示例中只使用通过许多类的超长比较方式。

但我仍然希望它更短。

if(annotationMirror.getAnnotationType().equals(annoClass)) 

不起作用。

我可以以某种方式比较类而不将它们变成名称吗?

标签: javaclassannotationsannotation-processingannotations-processing-messager

解决方案


我认为你在Types课堂上要求的是什么,你可以使用这样的isSameType方法

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;
                });

并且您不应该使用从类型名称获得的字符串文字进行比较,因为它在 intellij 和 eclipse 之间的工作方式可能不同。


推荐阅读