使用 Java 6 注释处理器获取泛型类型的限定类名

2024-01-26

我正在使用 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;
    }
}

任何提示将非常感激!


复制粘贴我的原答案 https://stackoverflow.com/a/19642482/761648:

这似乎是一个常见的问题,所以对于那些来自谷歌的人来说:还有希望。

The Dagger http://square.github.io/dagger/DI 项目根据 Apache 2.0 许可证获得许可,并包含一些用于在注释处理器中处理类型的实用方法。

特别是,Util可以在 GitHub 上查看完整课程(实用工具.java https://github.com/square/dagger/blob/master/compiler/src/main/java/dagger/internal/codegen/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;
    }
}

调用 Dagger 方法Element该处理器提供_bs field:

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

生成的源(当然是自定义的)。请注意很棒的嵌套泛型类型。

public java.util.Set<AnnotationTest.B<java.lang.Integer>> AnnotationTest.A.getBsGenerated()
{
    return this._bs;
}

编辑:调整概念以提取第一个通用参数的 TypeMirror,否则为 null:

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];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Java 6 注释处理器获取泛型类型的限定类名 的相关文章

随机推荐