gpt4 book ai didi

java - 我可以快速找到合适的MirrorAnnotation吗?

转载 作者:行者123 更新时间:2023-11-30 05:39:32 25 4
gpt4 key购买 nike

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

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

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

使用代码示例,thesethese ,结合我在那里找到的东西,我发现了一个复杂的方法:

@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

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

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

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

但我仍然希望它更短。

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

不起作用。

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

最佳答案

我认为您要求的内容存在于 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 之间的工作方式可能不同。

关于java - 我可以快速找到合适的MirrorAnnotation吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55937042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com