views:

767

answers:

2

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?

+4  A: 

It's not possible to add an annotation at runtime, it sounds like you need to introduce an adapter that module B uses to wrap the object from module A exposing the required annotated methods.

Tom
I second this. But I might consider to annotate the original, I don't see a big issue here. We do that usually, take the case of JPA Entities, which you pass to a remote EJB component to store in DB. And you use the same to populate your UI.
Adeel Ansari
Tom: Ah, of course. Perhaps with inheritance: Extend the class from module A, override the method in question and then annotate that?
Clayton
Vinegar: that's probably the easiest solution for me. I have tried to keep my "data model" separate from my "data implementation", but I honestly don't see a time when I would need to plug in a different data implementation.
Clayton
So, just go with the simple. Nonetheless, it would be handy to code your adapter later, whenever it is time. As you said you may consider inheritance for this, so dealing with the super type will do that.
Adeel Ansari
I decided to take a hybrid approach to this. For now, I've just annotated the original method (adding the dependency to modA), figuring that I can always just pull the annotation later and use an adapter. Thanks folks!
Clayton
+4  A: 

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).

ChssPly76