Maven example of annotation preprocessing and generation of classes in same compile process?

Jérôme Verstrynge picture Jérôme Verstrynge · Aug 6, 2011 · Viewed 12.1k times · Source

Does anyone have a clean example of a maven project preprocessing class annotations at compile time with subsequent generation of classes to be compiled in the same compilation process?

Does anyone have a step-by-step procedure to implement such a project?

Answer

Jérôme Verstrynge picture Jérôme Verstrynge · Aug 7, 2011

After navigating a lot in existing documentation on the net, I came up with the following:

What needs to be clarified:

  • In order to process annotations on a given project P, you first need an annotation processor compiled in a separate library S. P should have a dependency on S.
  • Implementing annotation processing in Java 5 is absolutely not the same thing as in Java 6.
  • Java 5 relies on a separate execution of apt. The corresponding tutorials here and here help understanding the basics of annotation processing and implementation in Java 5. Good reading for newbies.
  • Implementing annotation processing in Java 5 with Maven is tricky. One needs to add a local dependency to tools.jar to access the API described in these tutorials. Not clean. Some third-party plugins calling the apt are available, but not well documented.
  • Those using Java 6 should not jump-start implementing their processors according to the above tutorials.

Annotation Processing in Java 6 with Maven

  • A new package has been delivered in Java 6 to process annotations: the Pluggable Annotation Processing.
  • To implement a processor, create a separate Maven project. The above tutorial or this one explains how to proceed. This is our library S.
  • Then, create your project P and add a Maven dependency on S.
  • There is currently an issue with the maven-compiler-plugin, but a workaround is available here. Use it to compile your generated code as part of existing annotated code.

...and code generation

  • A great Java code generation library called CodeModel is available from Maven central. A good tutorial is available here. The javax annotation processing package offers some tools to generate output too.