【发布时间】:2014-07-10 07:02:26
【问题描述】:
例如,我有这样的代码:
@Retention(RetentionPolicy.SOURCE)
public @interface ClassAnnotation {
}
@ClassAnnotation
public class AnnotatedClass {
}
@ClassAnnotation
public class AnotherAnnotatedClass {
private AnnotatedClass someField;
private int intIsNotAnnotated;
}
这个处理器在编译时对其进行预处理:
@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
}
}
我需要检查一个字段的类型是否是一个用我的注解注解的类。不知何故,我有一个名为fieldTypeElement 的TypeElement,它可能代表来自someField 的AnnotatedClass 或来自示例中的intIsNotAnnotated 的int。如何获得@ClassAnnotation 的AnnotatedClass 的someField?我试过fieldTypeElement.getAnnotation(ClassAnnotation.class)和fieldTypeElement.getAnnotationMirrors(),但它分别返回null和空列表。
【问题讨论】:
标签: java annotations preprocessor annotation-processing