Adding Java Annotations at Runtime

Clayton picture Clayton · Oct 28, 2009 · Viewed 57.4k times · Source

Is it possible to add an annotation to an object (in my case in particular, a Method) at runtime?

For a bit more explanation: I have two modules, moduleA and moduleB. moduleB depends upon moduleA, which doesn't depend upon anything. (modA is my core datatypes and interfaces and such, modB is db/data layer) modB also depends on externalLibrary. In my case, modB is handing off a class from modA to externalLibrary, which needs certain methods to be annotated. The specific annotations are all part of externalLib and, as I said, modA doesn't depend on externalLib and I'd like to keep it that way.

So, is this possible, or do you have suggestions for other ways of looking at this problem?

Answer

ChssPly76 picture ChssPly76 · Oct 28, 2009

It's possible via bytecode instrumentation library such as Javassist.

In particular, take a look at AnnotationsAttribute class for an example on how to create / set annotations and tutorial section on bytecode API for general guidelines on how to manipulate class files.

This is anything but simple and straightforward, though - I would NOT recommend this approach and suggest you consider Tom's answer instead unless you need to do this for a huge number of classes (or said classes aren't available to you until runtime and thus writing an adapter is impossible).