Java byte-code injection

孤街醉人 提交于 2020-01-02 07:49:07

问题


I am trying to wrap my head around this concept. My questions are:

  1. Is this operation costly from a performance point of view, and if so, why?
  2. If I am trying to intercept some parameters being passed to a method by injecting some code after the method is called, does this injection happen once or does it happen every time the method is called?
  3. Where does this injection code reside? In the application source itself or somewhere else?

回答1:


You can achieve bytecode injection with Java Agents.

A java Agent is a library that intercepts the bytecode loading at the classloader, and enhances it before it is loaded in the JVM. Of course, such a library usually relies on bytecode manipulation librairies such as Javassist, ASM or CGLib. So the bytecode manipulation is only done once, when the class is loaded.

See the official Javadoc : http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html

This article explains how to do pretty much what you want to: http://today.java.net/pub/a/today/2008/04/24/add-logging-at-class-load-time-with-instrumentation.html

Also, if you're really interested in bytecode fundamentals, this article from one of the JRebel developers should please you: http://arhipov.blogspot.com/2011/01/java-bytecode-fundamentals.html

Finally, you can take a look at Seren, a librairy I just began to write. It is a Java Agent that enhances serializable classes. It's just the beginning, but it works. https://github.com/oliviercroisier/seren



来源:https://stackoverflow.com/questions/8493056/java-byte-code-injection

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