John Goering
John Goering

Reputation: 39030

Retro-actively add Java annotations to methods?

Is there a way to modify .class files in order to add Java annotations to certain methods? Basically I want to traverse methods of each class file in a jar file and annotate certain ones. Note that this is not at run-time while using the jar file. Rather, after I'm done I want to have modified class files with the annotations.

I do have access to the source code, so if there's an automatic source code modifier, that would work as well...

I'm assuming I'll need a tool such as Javassist or ASM. If so, which one should I use and how would I go about it?

Upvotes: 3

Views: 951

Answers (2)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298818

Actually, this is a classic use case for AspectJ:

declare @method : public * BankAccount+.*(..) : @Secured(role="supervisor")

While I will grant you that direct byte code manipulation is more powerful, AspectJ is much more user-friendly, and it immediately gives you compiler warnings when you are doing something wrong.

Also, if you use Load Time Weaving, you can leave the original library jar unchanged, because the weaving happens at class-load time.

Reference:

Upvotes: 8

John Goering
John Goering

Reputation: 39030

Googling for an hour or so turned this article up which seems to completely answer my question: use ASM. To write class files using the changed bytecode, use ClassWriter.

Well, time to get to work then, I guess. :)

Upvotes: 4

Related Questions