简体   繁体   中英

How do I use Annotation Processing API in runtime?

I have and followed several Annotation Processing Tool (APT) guides (such as 1 and 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?

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.

Did you specify that your annotation is available at runtime using the RetentionPolicy ? If not you need to use @Retention annotation on yours.

@Retention(RetentionPolicy.RUNTIME)

public @interface MyAnnotation {
    String[] parameters();
    String[] exceptions();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM