6

I have a couple of packages in a library that contain annotations and base classes. I'm extending javax.annotation.processing.AbstractProcessor in the context of this question.

Is there a way to get a List/Array/Set of java.lang.TypeElement for all types declared in a package? Or even Elements?

Currently I have a workaround that marks classes into groups by using an annotation on a Type that solely exists to denote groups of related objects in the library. Is there a simpler way to group Types together by package (i.e. location) rather than explicit declaration?

Preston Garno
  • 1,175
  • 10
  • 33

1 Answers1

5

Found the answer - I used the ProcessingEnvironment instance variable (in my AbstractProcessor subclass) to get javax.lang.model.util.Elements instance to perform really helpful Element/Type/Package access:

   List<TypeMirror> typeMirrorsInPackage = processingEnv.getElementUtils()
                .getPackageElement("com.example.sample.annotations")
                .getEnclosedElements()
                .stream()
                .map(Element::asType)
                .filter(mirror -> mirror.getKind() == TypeKind.DECLARED)
                .collect(Collectors.toList());

Be careful, according to the javadoc: If this is a generic element, a prototypical type is returned. This is the element's invocation on the type variables corresponding to its own formal type parameters. Apparently the Types class has more helpful utility methods to handle generics.

Preston Garno
  • 1,175
  • 10
  • 33
  • What if the package is unknown? How to get all packages? – hohserg Oct 14 '20 at 16:17
  • 1
    @hohserg You can retrieve all packages enclosed in a ModuleElement, for example : `List elementPackages(Element element, Elements elements) { return elements.getModuleOf(element).getEnclosedElements(); }`. – Kabhal Sep 02 '21 at 15:44