Monday, March 14, 2022

[SOLVED] How do I use Annotation Processing API in runtime?

Issue

I have and followed several Annotation Processing Tool (APT) guides (such as 1 and href="http://blog.christoffer.me/2011/08/how-to-enforce-static-methods-on-class.html" rel="noreferrer">2) on the Internet and have managed to get it working in compiler/ build time, and even got it working in Eclipse.

Is there a way I can use APT in run time to get a list of Types (Classes) using my annotation.

I wrote something like:

@SupportedAnnotationTypes("com.domain.MyAnnotation")
public class MyAbstractProcessor extends AbstractProcessor {

    public static Map<Element, MyAnnotation> patches = new HashMap<Element, MyAnnotation>();

    @Override
    public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) {

        // Get all classes that has the annotation
        Set<? extends Element> classElements = roundEnvironment.getElementsAnnotatedWith(MyAnnotation.class);

        // For each class that has the annotation
        for (final Element classElement : classElements) {

            patches.put(classElement, annotation);

So MyAbstractProcessor.patches would be populate with a list of classes using the annotation. A noble idea, apart from the flaw that this APT is executing at build time, and not run time.

Is it even possible to use APT in run time?

Or am I using the wrong frameworks to get what I want?


Solution

You can access the annotations at run time using reflection - getAnnotations.

To get a list of classes (in your classpath) using your annotation, you could - at runtime - iterate through all the classes testing if they have that annotation.

Alternatively - at build time - you could construct a class with a list of classes.



Answered By - emory
Answer Checked By - Gilberto Lyons (WPSolving Admin)