使用Annotation处理器获取annotatted类的声明字段

时间:2013-05-10 18:01:36

标签: java annotations processor

我有一个注释处理器,我需要获取与元素相关联的类,以便我可以检索其声明的字段:

@Override
public boolean process(Set<? extends TypeElement> annotations,
        RoundEnvironment roundEnv) {
    String className = null;
    String packageName = null;
    String fqClassName = null;
    List<String> fields = new LinkedList<String>();
    for (Element elem : roundEnv.getElementsAnnotatedWith(FieldConstant.class)) {
        if (elem.getKind() == ElementKind.CLASS) {
            //              Encrypt encrypt = elem.getAnnotation(Encrypt.class);
            //              String message = "annotation found in " + elem.getSimpleName();
            //              processingEnv.getMessager().printMessage(Kind.NOTE, message);
            TypeElement classElement = (TypeElement) elem;
            PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();
            className = classElement.getSimpleName().toString();
            for(Field field : classElement.getClass().getDeclaredFields()){
               do something...
            }
      .....

显然,className.getClass()会返回TypeElement.class,但我想检索带注释的类。我怎么能这样做?

1 个答案:

答案 0 :(得分:8)

您不能对正常编译的代码使用反射,因为代码可能已在上一次传递中被修改或生成(如何将它们添加到类路径中?)。

然而,好消息是您可以使用javax.lang.model中的包来获取字段的属性。

以下示例将所有字段定义打印到System.out(可能缺少一些关键字,例如transient):

@Override
public boolean process(Set<? extends TypeElement> annotations,
        RoundEnvironment roundEnv) {
    for (Element elem : roundEnv.getElementsAnnotatedWith(FieldConstant.class)) {
        if (elem.getKind() == ElementKind.CLASS) {
            // print fields
            for (Element enclosedElement : elem.getEnclosedElements()) {
                if (enclosedElement.getKind() == ElementKind.FIELD) {
                    Set<Modifier> modifiers = enclosedElement.getModifiers();
                    StringBuilder sb = new StringBuilder();
                    if (modifiers.contains(Modifier.PRIVATE)) {
                        sb.append("private ");
                    } else if (modifiers.contains(Modifier.PROTECTED)) {
                        sb.append("protected ");
                    } else if (modifiers.contains(Modifier.PUBLIC)) {
                        sb.append("public ");
                    }
                    if (modifiers.contains(Modifier.STATIC))
                        sb.append("static ");
                    if (modifiers.contains(Modifier.FINAL))
                        sb.append("final ");
                    sb.append(enclosedElement.asType()).append(" ").append(enclosedElement.getSimpleName());
                    System.out.println(sb);
                }
            }
        }
    }
    ...