문제

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?

도움이 되었습니까?

해결책 2

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

다른 팁

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:

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top