fik*_*r4n 5 java preprocessor annotations annotation-processing
例如,我有以下代码:
@Retention(RetentionPolicy.SOURCE)
public @interface ClassAnnotation {
}
@ClassAnnotation
public class AnnotatedClass {
}
@ClassAnnotation
public class AnotherAnnotatedClass {
private AnnotatedClass someField;
private int intIsNotAnnotated;
}
Run Code Online (Sandbox Code Playgroud)
并在编译时对该处理器进行预处理:
@SupportedAnnotationTypes({ "com.example.ClassAnnotation" })
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class AwesomeProcessor extends AbstractProcessor {
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
// Skipped for brevity...
// For each annotated class
for (Element e : roundEnv.getElementsAnnotatedWith(ClassAnnotation.class)) {
// Skipped for brevity...
// For each field
for (Element ee : classElement.getEnclosedElements()) {
// Skipped for brevity... (of course there's kind checking)
TypeMirror fieldType = fieldElement.asType();
TypeElement fieldTypeElement = (TypeElement) processingEnv.
getTypeUtils().asElement(fieldType);
}
}
// Skipped for brevity
}
}
Run Code Online (Sandbox Code Playgroud)
我需要检查字段的类型是否是使用我的注释进行注释的类。我TypeElement
以某种方式得到了一个命名fieldTypeElement
,它可能AnnotatedClass
来自someField
或int
来自intIsNotAnnotated
示例。如何获得@ClassAnnotation
的AnnotatedClass
的someField
?我尝试了fieldTypeElement.getAnnotation(ClassAnnotation.class)
和fieldTypeElement.getAnnotationMirrors()
,但它分别返回null和空列表。
我认为您以某种方式弄错了,TypeElement
但不幸的是,该部分代码丢失了。
这个简单的示例按预期工作:
processingEnv.getElementUtils().getTypeElement("AnnotatedClass").getAnnotationMirrors()
Run Code Online (Sandbox Code Playgroud)
包含@ClassAnnotation
。
要获得TypeElement
某个领域的知识,您必须
DeclaredType
TypeElement
尽管不需要获取元素的注释,但最后一步不是必需的:
Element field = // ...
List<? extends AnnotationMirror> annotationMirrors =
((DeclaredType) field.asType()).asElement().getAnnotationMirrors();
Run Code Online (Sandbox Code Playgroud)
更新的代码应该可以运行,我已经对其进行了测试,并且运行良好。该错误必须在其他地方。其他要检查的内容:
RetentionPolicy
注释的。无,CLASS
或RUNTIME
很好,但是SOURCE
不起作用