Search code examples
javaannotationsannotation-processing

Get package name of a annotated class within AnnotationProcessor


I have a class which I process with an AnnotationProcessor. While in the process I have an instance of javax.lang.model.element.Element where I can i.e. get the name of the the annotated class by .getSimpleName(). What I know need is the packageName (com.software.cool) of the annotated class.

Any idea how to go through the API to receive it?


Solution

  • You definitely do not want to use getQualifiedName: it will produce surprising results in some cases. For example, it is impossible to distinguish last part of package name and parent class of inner classes: in "java.util.Map.Entry" is "Map" a part of package name or the name of containing class for Entry? What if instead of "java.util.Map.Entry" it is "a.b.c.d" (a typical case for Proguard-processed code)?

    Likewise, for classes in default (unnamed) package there won't be anything before the dot…

    With getQualifiedName your parsing code will be complex and unreliable. Generally speaking, when you have to use string representations of Element you are doing something wrong.

    This is the proper pattern for getting package of element:

    Element enclosing = element;
    while (enclosing.getKind() != ElementKind.PACKAGE) {
        enclosing = enclosing.getEnclosingElement();
    }
    PackageElement packageElement = (PackageElement) enclosing;
    

    This will correctly get package in all cases.