[英]Java annotation processor, annotation types with annotations
我正在使用注释处理器来处理方法参数的注释。
public void multiply(@IntArg int a){
...
}
用于参数的注释类型具有注释@Argument
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.PARAMETER})
@Argument
public @interface IntArg {
}
现在,当我的注释处理器运行时,我想检查参数注释( @IntArg
)是否具有@Argument
注释。 我通过执行以下代码来做到这一点。
VariableElement param = ... //The parameter
for (AnnotationMirror mirror : param.getAnnotationMirrors()) {
Argument arg = mirror.getAnnotationType().getAnnotation(Argument.class);
if(arg != null) {//Args is always null
...
}
}
由于某些原因, arg
始终为null。 为什么不返回注释?
我认为您需要的是:
VariableElement param = ...;
for (AnnotationMirror mirror : param.getAnnotationMirrors()) {
DeclaredType t = mirror.getAnnotationType();
// (Filter out ErrorType: see my addendum.)
if (t.getKind() == TypeKind.DECLARED) {
Element e = t.asElement();
// (This should always be true.)
if (e.getKind() == ElementKind.ANNOTATION_TYPE) {
Argument a = e.getAnnotation(Argument.class);
// ...
}
}
}
虽然
TypeElement
表示类或接口元素 ,但DeclaredType表示类或接口类型 ,后者是前者的使用(或调用 )。
因此,如果您想以某种方式检查声明,则需要元素而不是类型。
注意,我也可以将e
TypeElement
为上述代码片段中的TypeElement
。 没有什么特别的理由。
关于我的编辑的快速附录:我认为在此处检查TypeKind
可能是正确的,因为getAnnotationType()
可能返回ErrorType
。 如果我做这样的事情,可能会发生这种情况:
void m(@IntArg @TypeWhichDoesntExist int arg0) {
}
其中TypeWhichDoesntExist
是不存在的类型,例如,因为它没有被导入,因为它是由另一个注释处理器生成的@interface
或完全不存在的类型。 (注释处理器可能会使用未编译的代码来调用。)
我认为这不会对我的示例之前的编写方式造成任何问题,但我认为有必要指出这种情况可能会发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.