Adding programmatic annotations to a Java class

Viewed 2351

Usage example:
I want to put on class fields a custom annotation @MyContainer and then add automatically on all such fields relevant Hibernate annotations (depending on field type and properties).
In additional I need to add JAXB XmlType annotation to the class and base the type name on the class name.
I would want additionally to add annotations to fields based on thier types, etc. All added annotations should be available at run time (So hibernate / JAXB can find them).
I'm aware of the following options:

  1. Pre-processing class source (bad option)
  2. Processing during compilation with javax.annotation.processing APIs
  3. Post compilation manipulation with tools such as Java Assist
  4. Manipulation during class loading with java.lang.instrument APIs
  5. Doing it with AspectJ (not powerful enough)

My primary goals are:

  1. Keep sync between class and source for debugging
  2. Support working from both Maven and IDE (Eclipse / Intellij)

I'll appreciate if people who already done such things can recommend the best approach for such a task (and perhaps potential pitfalls).

5 Answers
Related