(blog-of ‘Alex’)

My blog about software development and other things

How to: Write and debug annotations processor

This is a short but comprehensive guide on how to write and debug your own annotations processor. I followed these steps in Java 6, I see no reason why it shouldn’t just as well work on Java 7.

So, step 1:

Produce jar for your annotations processor. Let’s it will be say ann-proc.jar. You’ll need extra dependency if you use sun-specific code model entities. These are defined in the JDK’s tools.jar. Your annotation processor’s dependency section may look as follows (assuming that you use maven to build it):

<dependency>
    <groupId>com.sun</groupId>
    <artifactId>tools</artifactId>
    <version>1.6.0</version>
    <scope>system</scope>
    <systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>

Then create (or open if you already have one) another jar you want to process with your annotations processor. Let’s say you have it, its name is my.jar.

Add the following file (which in fact is a SPI configuration file) to my.jar resources folder

    resources
    |
    + /META-INF/services
    |
    + javax.annotation.processing.Processor

The contents of this file would look as follows:

com.ann.proc.processor.MyAnnotationProcessor

That’s it, do mvn clean install on the my.jar package having installed ann-proc.jar and see the effect.

If you want to debug your annotations processor, you may want to use mvnDebug, e.g. mvnDebug clean compile. Once you start compilation (which subsequently should trigger your annotation processor) attach your IDE to the 8000 debug port and see debugger hitting breakpoints in your annotation processor’s source.