Get package name and parametrized type from a field element - Annotation Processor
Asked Answered
G

1

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?

Gamine answered 21/6, 2017 at 20:0 Comment(0)
L
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.

Litton answered 22/6, 2017 at 3:36 Comment(2)
Are there any consequences of comparing DeclaredType with instanceof and element.asType().getKind() == TypeKind.DECLARED)?Gamine
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.Litton

© 2022 - 2024 — McMap. All rights reserved.