3

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

@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但我想检索带注释的类。我怎样才能做到这一点?

4

1 回答 1

10

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

然而,好消息是您可以使用其中的包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);
                }
            }
        }
    }
    ...
于 2013-12-27T12:14:39.317 回答