Adding/modifying annotations in a java project

♀尐吖头ヾ 提交于 2019-12-04 05:46:56

I looked into this more and as a summary, here's what I found:

  • Java language does not allow changing annotations during runtime.
  • One can use Javassist to modify the java bytecode but it does not work on platforms like Android.
  • One can use ASM but that involves dealing with Java assembly (an example is here: http://community.jboss.org/thread/150002).

Primarily due to JAXB not being present on Android (and other reasons) we switched to JSON and starting using Jackson as the implementation. One benefit of this change was the ability to use what Jackson calls "mixed-in annotations" which is exactly what I was looking for.

Here's the link that explains it more: http://www.cowtowncoder.com/blog/archives/2009/08/entry_305.html

Short of hacking the .class bytecode during runtime, this can't be done. You can use Javassist if you really want to dynamically change the bytecode of the library classes during runtime but in the bigger picture this will probably end up blowing up badly.

I would suggest that you just annotate the library and recompile if its your codebase. If it isn't, you can still wrap the library classes/interfaces in your own classes/interfaces through inheritance and annotate there. Either way, I think it would be better to annotate in the code than through runtime bytecode hacking. Added bonus, annotations in the source will be seen by IDEs, allowing the IDE to better assist you.

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