Retro-actively add Java annotations to methods?

半世苍凉 提交于 2019-12-20 02:15:13

问题


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?


回答1:


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:

  • Declare Annotation
  • AspectJ in Action (book)



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



来源:https://stackoverflow.com/questions/4826946/retro-actively-add-java-annotations-to-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!