Search code examples
javaannotations

How can I access a RetentionPolicy.CLASS java annotation?


Is there a way to configure a ClassLoader or a JVM to load annotations with CLASS retention policy, so I can access them using reflection?

This is useful for compile-time post-processing, as mentioned here. I annotate some of my classes in order to generate an antlib.xml file automatically. I would prefer if my annotation could have CLASS retention policy, so that it does not create runtime dependencies.


Solution

  • javac can process source and class level annotations, with the -processor option. See javax.annotation.processing.AbstractProcessor. (Since java 1.6).

    I started using it while compiling .java files. Apparently it can also be used to process CLASS annotations with .class input files. I haven't tried this because I'm using ant to compile, and ant does not seem to pass .class files to the compiler.

    I have to do a full compile when I want to process all the annotations in my project.