我正在使用注释处理器来处理方法参数的注释。
public void multiply(@IntArg int a){
...
}用于参数的注解类型有一个注释@参数
@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总是空的。注释没有返回的原因吗?
发布于 2017-08-29 21:09:36
我想你需要的是:
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;只是没有特别的理由。
关于我的编辑的快速补充:我认为在这里检查TypeKind可能是正确的,因为getAnnotationType()可以返回一个ErrorType。如果我做了这样的事,这可能会发生:
void m(@IntArg @TypeWhichDoesntExist int arg0) {
}其中TypeWhichDoesntExist是一种不存在的类型,例如,因为它不是导入的,因为它是由另一个注释处理器生成的@interface,或者因为它完全不存在。(注释处理器可以使用不编译的代码调用。)
我不认为这会引起问题,我的例子是写之前,但我认为值得指出,这是可能发生的。
https://stackoverflow.com/questions/45948023
复制相似问题