追溯性地向方法添加Java注释?
有没有办法修改 .class 文件以便向某些方法添加 Java 注释?基本上我想遍历 jar 文件中每个类文件的方法并注释某些方法。请注意,这不是在使用 jar 文件时的运行时。相反,完成后我想用注释修改类文件。
我确实可以访问源代码,所以如果有自动源代码修饰符,那也可以工作......
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,这是 AspectJ 的一个经典用例:
虽然我承认直接字节码操作更强大,但 AspectJ 对用户更加友好,并且当您做错事时它会立即向您发出编译器警告。
另外,如果您使用加载时间编织,您可以将原始库 jar 未更改,因为编织发生在类加载时。
参考:
Actually, this is a classic use case for AspectJ:
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:
谷歌搜索一个小时左右,找到了这篇文章,这似乎完全回答了我的问题:使用ASM。要使用更改后的字节码编写类文件,请使用 ClassWriter。
好吧,我想是时候开始工作了。 :)
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. :)