java - 我可以在短时间内找到合适的 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))
不起作用。
我可以以某种方式比较类而不将它们变成名称吗?
解决方案
我认为你在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 之间的工作方式可能不同。
推荐阅读
- google-analytics - 点击用户身份验证电子邮件链接后的 Google Analytics(分析)目标
- wpf - 使用什么面板
- python - 为什么 Homography 不在检测到的对象上绘制框?
- java - 尽管使用了 Maven Shade 插件,但仍会引发 NoClassDefFoundError 的可能原因是什么?
- hibernate - Spring Data JPQL 不过滤 OneToMany 关系的关联实体
- c# - 当 JSON 字典为空时,反序列化 JSON 字符串失败
- c# - 当存储为 UTC 时,如何全局序列化和反序列化 Date 与 DateTime?
- javascript - 在不丢失 this 关键字的情况下对方法进行分组
- spring - Spring Boot + REST API + 社交登录
- android - RecyclerView custommAdapter 和 MainActivity