使用Java 6注解处理器获取泛型类型的合格类名

15

我正在使用JDK 6的注解处理API开发一个小型代码生成器,但在尝试获取类中字段的实际泛型类型时遇到了困难。更明确地说,假设我有这样一个类:

@MyAnnotation
public class User {         
    private String id;
    private String username;
    private String password;
    private Set<Role> roles = new HashSet<Role>();
    private UserProfile profile;
}

以下是我的注解处理器类:

@SupportedAnnotationTypes({ "xxx.MyAnnotation" })
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class MongoDocumentAnnotationProcessor extends AbstractProcessor {

    private Types typeUtils = null;
    private Elements elementUtils = null;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        typeUtils = processingEnv.getTypeUtils();
        elementUtils = processingEnv.getElementUtils();
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        debug("Running " + getClass().getSimpleName());
        if (roundEnv.processingOver() || annotations.size() == 0) {
            return false;
        }
        for (Element element : roundEnv.getRootElements()) {
            if (element.getKind() == ElementKind.CLASS && isAnnotatedWithMongoDocument(element)) {
                for (VariableElement variableElement : ElementFilter.fieldsIn(element.getEnclosedElements())) {
                    String fieldName = variableElement.getSimpleName().toString();
                    Element innerElement = typeUtils.asElement(variableElement.asType());
                    String fieldClass = "";
                    if (innerElement == null) { // Primitive type
                        PrimitiveType primitiveType = (PrimitiveType) variableElement.asType();
                        fieldClass = typeUtils.boxedClass(primitiveType).getQualifiedName().toString();
                    } else {
                        if (innerElement instanceof TypeElement) {
                            TypeElement typeElement = (TypeElement) innerElement;
                            fieldClass = typeElement.getQualifiedName().toString();
                            TypeElement collectionType = elementUtils.getTypeElement("java.util.Collection");
                            if (typeUtils.isAssignable(typeElement.asType(), collectionType.asType())) {
                                TypeVariable typeMirror = (TypeVariable)((DeclaredType)typeElement.asType()).getTypeArguments().get(0);
                                TypeParameterElement typeParameterElement = (TypeParameterElement) typeUtils.asElement(typeMirror);
                                // I am stuck here. I don't know how to get the
                                // full qualified class name of the generic type of
                                // property 'roles' when the code processes the User
                                // class as above. What I want to retrieve is the
                                // 'my.package.Role' value
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    private boolean isAnnotated(Element element) {
        List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
        if (annotationMirrors == null || annotationMirrors.size() == 0) return false;
        for (AnnotationMirror annotationMirror : annotationMirrors) {
            String qualifiedName = ((TypeElement)annotationMirror.getAnnotationType().asElement()).getQualifiedName().toString();
            if ("xxx.MyAnnotation".equals(qualifiedName)) return true;
        }
        return false;
    }
}

非常感谢您提供任何提示!


可能是Java泛型:在运行时访问泛型类型的重复问题。 - Mike Samuel
7
我认为注解处理发生在编译之前,因此类型擦除还没有发生。此外,我正在使用Java注解处理器API而不是反射API,因此我认为这是可能的。如果我错了,请纠正我。 - Tinh Truong
4个回答

11

以下是我原始答案的复制粘贴:(原文链接)

这似乎是一个常见问题,所以对于那些从Google进来的人:有希望。

Dagger DI项目在Apache 2.0许可证下授权,并包含一些用于在注释处理器中使用类型的实用程序方法。

特别是,Util类可以在GitHub上完整查看(Util.java),并定义了一个方法public static String typeToString(TypeMirror type)。 它使用TypeVisitor和一些递归调用来构建类型的字符串表示形式。 以下是参考代码片段:

public static void typeToString(final TypeMirror type, final StringBuilder result, final char innerClassSeparator)
{
    type.accept(new SimpleTypeVisitor6<Void, Void>()
    {
        @Override
        public Void visitDeclared(DeclaredType declaredType, Void v)
        {
            TypeElement typeElement = (TypeElement) declaredType.asElement();

            rawTypeToString(result, typeElement, innerClassSeparator);

            List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
            if (!typeArguments.isEmpty())
            {
                result.append("<");
                for (int i = 0; i < typeArguments.size(); i++)
                {
                    if (i != 0)
                    {
                        result.append(", ");
                    }

                    // NOTE: Recursively resolve the types
                    typeToString(typeArguments.get(i), result, innerClassSeparator);
                }

                result.append(">");
            }

            return null;
        }

        @Override
        public Void visitPrimitive(PrimitiveType primitiveType, Void v) { ... }

        @Override
        public Void visitArray(ArrayType arrayType, Void v) { ... }

        @Override
        public Void visitTypeVariable(TypeVariable typeVariable, Void v) 
        {
            result.append(typeVariable.asElement().getSimpleName());
            return null;
        }

        @Override
        public Void visitError(ErrorType errorType, Void v) { ... }

        @Override
        protected Void defaultAction(TypeMirror typeMirror, Void v) { ... }
    }, null);
}

我正在忙于自己的项目,该项目生成类扩展。Dagger方法适用于复杂情况,包括泛型内部类。我得到了以下结果:

我的测试类具有需要扩展的字段:

public class AnnotationTest
{
    ...

    public static class A
    {
        @MyAnnotation
        private Set<B<Integer>> _bs;
    }

    public static class B<T>
    {
        private T _value;
    }
}

在处理器为_bs字段提供的Element上调用Dagger方法:

accessor.type = DaggerUtils.typeToString(element.asType());

生成的源代码(自定义的,当然)。请注意嵌套的泛型类型。
public java.util.Set<AnnotationTest.B<java.lang.Integer>> AnnotationTest.A.getBsGenerated()
{
    return this._bs;
}

编辑:将概念调整为提取第一个泛型参数的TypeMirror,否则为空:

public static TypeMirror getGenericType(final TypeMirror type)
{
    final TypeMirror[] result = { null };

    type.accept(new SimpleTypeVisitor6<Void, Void>()
    {
        @Override
        public Void visitDeclared(DeclaredType declaredType, Void v)
        {
            List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
            if (!typeArguments.isEmpty())
            {
                result[0] = typeArguments.get(0);
            }
            return null;
        }
        @Override
        public Void visitPrimitive(PrimitiveType primitiveType, Void v)
        {
            return null;
        }
        @Override
        public Void visitArray(ArrayType arrayType, Void v)
        {
            return null;
        }
        @Override
        public Void visitTypeVariable(TypeVariable typeVariable, Void v)
        {
            return null;
        }
        @Override
        public Void visitError(ErrorType errorType, Void v)
        {
            return null;
        }
        @Override
        protected Void defaultAction(TypeMirror typeMirror, Void v)
        {
            throw new UnsupportedOperationException();
        }
    }, null);

    return result[0];
}

3

看起来有几个问题。首先,isAssignable()函数没有按预期工作。其次,在上面的代码中,您试图获取Set类型(T)的通用参数,而不是变量声明(Role)。

尽管如此,以下代码应该演示了您需要的内容:

@SupportedAnnotationTypes({ "xxx.MyAnnotation" })
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class MongoDocumentAnnotationProcessor extends AbstractProcessor {
    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        if (roundEnv.processingOver() || annotations.size() == 0) {
            return false;
        }
        for (Element element : roundEnv.getRootElements()) {
            if (element.getKind() == ElementKind.CLASS && isAnnotatedWithMongoDocument(element)) {
                System.out.println("Running " + getClass().getSimpleName());
                for (VariableElement variableElement : ElementFilter.fieldsIn(element.getEnclosedElements())) {
                    if(variableElement.asType() instanceof DeclaredType){
                        DeclaredType declaredType = (DeclaredType) variableElement.asType();

                        for (TypeMirror typeMirror : declaredType.getTypeArguments()) {
                            System.out.println(typeMirror.toString());
                        }
                    }
                }
            }
        }
        return true;  //processed
    }

    private boolean isAnnotatedWithMongoDocument(Element element) {
        return element.getAnnotation(MyAnnotation.class) != null;
    }
}

这段代码应该输出:
xxx.Role

那段代码不会输出 xxx.Role...你的代码中至少有两个 2xN 的 System.out.println(...),所以它百分之百不会这样做。 - searchengine27

1

尽管其他答案都有很多好的观点,但并没有真正展示出你所面临的问题及其解决方案。

你代码中的问题在这里。

TypeElement collectionType = elementUtils.getTypeElement("java.util.Collection");
if (typeUtils.isAssignable(typeElement.asType(), collectionType.asType())) {
...

您的类型没有扩展 java.util.Collection,而是扩展了 java.util.Collection<*>。让我们重写上面的代码块以反映这一点:

WildcardType WILDCARD_TYPE_NULL = this.typeUtils.getWildcardType(null, null);
final TypeElement collectionTypeElement = this.elementUtils.getTypeElement(Collection.class.getName());
TypeMirror[] typex = {WILDCARD_TYPE_NULL};
DeclaredType collectionType=this.typeUtils.getDeclaredType(collectionTypeElement, typex);
if (typeUtils.isAssignable(typeElement.asType(), collectionType)){ 
 ...

那样应该让它工作。

0

使用Java 11,您可以将TypeMirror转换为Type.ClassType。此代码

// classToIntrospect is a TypeMirror of java.util.List<it.firegloves.sragen.Dog>
(ClassType)classToIntrospect

将被评估

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接