Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 582
mallaudin Avatar asked Jun 21 '17 20:06

mallaudin


1 Answers

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.

like image 199
Radiodef Avatar answered Nov 04 '22 16:11

Radiodef