Copy-paste my original answer :
This seems to be a common question, so for those coming from Google: there is hope.
Dagger The DI project is licensed under the Apache 2.0 license and contains some utility for working with types in the annotation processor.
In particular, the Util
class can be fully viewed in GitHub ( Util.java ) and defines the method public static String typeToString(TypeMirror type)
. It uses TypeVisitor and some recursive calls to create a string representation of the type. Here is a snippet for reference:
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(", "); }
I am busy with my own project that generates class extensions. The Dagger method works for complex situations, including common inner classes. I have the following results:
My test class with field extension:
public class AnnotationTest { ... public static class A { @MyAnnotation private Set<B<Integer>> _bs; } public static class B<T> { private T _value; } }
Calling the Dagger method on the Element
processor provides the _bs
field:
accessor.type = DaggerUtils.typeToString(element.asType());
Generated source (custom, of course). Pay attention to the amazing nested generic types.
public java.util.Set<AnnotationTest.B<java.lang.Integer>> AnnotationTest.A.getBsGenerated() { return this._bs; }
EDIT: Adapting the concept to extract TypeMirror of the first common argument, null otherwise:
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]; }