如何在Java注释处理中获取字段的类型注释?

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来自someFieldint来自intIsNotAnnotated示例。如何获得@ClassAnnotationAnnotatedClasssomeField?我尝试了fieldTypeElement.getAnnotation(ClassAnnotation.class)fieldTypeElement.getAnnotationMirrors(),但它分别返回null和空列表。

kap*_*pex 5

我认为您以某种方式弄错了,TypeElement但不幸的是,该部分代码丢失了。

这个简单的示例按预期工作:

processingEnv.getElementUtils().getTypeElement("AnnotatedClass").getAnnotationMirrors()
Run Code Online (Sandbox Code Playgroud)

包含@ClassAnnotation

要获得TypeElement某个领域的知识,您必须

  1. 获取字段的类型
  2. 将类型转换为 DeclaredType
  3. 获取声明的类型的元素
  4. 将元素转换为 TypeElement

尽管不需要获取元素的注释,但最后一步不是必需的:

Element field = // ... 
List<? extends AnnotationMirror> annotationMirrors =
    ((DeclaredType) field.asType()).asElement().getAnnotationMirrors();
Run Code Online (Sandbox Code Playgroud)

更新的代码应该可以运行,我已经对其进行了测试,并且运行良好。该错误必须在其他地方。其他要检查的内容:

  • 确保构建良好,有时构建步骤失败并且未注意到使用旧代码
  • 检查RetentionPolicy注释的。无,CLASSRUNTIME很好,但是SOURCE不起作用