Can I modify the byte code of a Java method in the runtime?

Calvin Kwok picture Calvin Kwok · Oct 9, 2013 · Viewed 8k times · Source

I am writing a plugin of another large java program .

I want to modify some byte code of some java method of the java program during runtime, so that I can intercept the method calls (namely, inject some hooking code into the method).

Any way can achieve this?

PS:

I've checked the following approaches:

1.change the classloader of the java program. (we CANNOT change it)
2.use java proxy. (We CANNOT use java proxy, because java proxy would create a new proxy object. We DON'T use the proxy object. We need to hook the java program's object, and Use that object)
3. use -javaagent option ( we CANNOT add the commandline option for the java program.)

PS more [Edited again]:
My classes was loaded by ext class loader (I put my jar files in JAVA_HOME\lib\ext folder). The large java program is an applet program loaded by Browser. When the browser start the applet, it also loads my classes.

PS more more [Edited again]:
Although it's running in Applet. I can have full permission. Because I can modify java.policy and java.security file.

Thanks,
Calvin

Answer

Anish Antony picture Anish Antony · Oct 9, 2013

Just use -javaagent opiton, which is used to modify the bytecode at runtime. You can find more about -javaagent from This Link or from This Link