8

How can I get package name, generic type and Parametrized type from a type from a field element in Annotation processor?

Say, if Element.asType returns java.util.List<String>, I want to get

  • Package name java.util
  • Generic type List<E> or raw type List (preferably raw type)
  • Actual Type String

Is there any method in element utils, type utils?

mallaudin
  • 4,744
  • 3
  • 36
  • 68

1 Answers1

19

Getting the package java.util:

Element        e   = processingEnv.getTypeUtils().asElement(type);
PackageElement pkg = processingEnv.getElementUtils().getPackageOf(e);

Getting the raw type List:

TypeMirror raw = processingEnv.getTypeUtils().erasure(type);

Getting the type arguments e.g. String:

if (type.getKind() == TypeKind.DECLARED) {
    List<? extends TypeMirror> args =
        ((DeclaredType) type).getTypeArguments();
    args.forEach(t -> {/*...*/});
}

See: Types.asElement, Elements.getPackageOf, Types.erasure and DeclaredType.getTypeArguments.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • Are there any consequences of comparing `DeclaredType` with `instanceof` and `element.asType().getKind() == TypeKind.DECLARED)`? – mallaudin Jun 22 '17 at 16:27
  • 1
    If you needed to be sure that the type really is a declared type, then `getKind()` probably is more technically correct. The documentation requires that an empty list be returned if there are no type arguments so whether or not it would be an error not to is a bit ambiguous. On the other hand, if you have a `TypeElement`, then you don't need to check since it will always be a `DeclaredType`. – Radiodef Jun 23 '17 at 04:26