3

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?

Epaga
  • 38,231
  • 58
  • 157
  • 245
  • It's certainly possible to do this by adding the proper attributes to the methods fields of the .class file. I don't have much experience using tools to do this, though. – templatetypedef Jan 28 '11 at 10:06
  • that's encouraging I guess...hope someone will answer soon. :) – Epaga Jan 28 '11 at 10:14

2 Answers2

8

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:

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
4

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

Epaga
  • 38,231
  • 58
  • 157
  • 245