I'm currently trying to edit the bytecode of a java class after it has been loaded by the JVM.
I use Java 8 and ASM 5.0.3. I can't change the command line or the JVM arguments.
Here is a minimal example of what I'm trying to do:
import org.objectweb.asm.*;
// Is in a library
class ExampleObject {
public void exampleMethod(Object o) {
System.out.println("Body " + o);
}
}
public class Example {
// Comes from the same library
public static final ExampleObject exampleObject = new ExampleObject();
public static void main(String[] args) {
exampleObject.exampleMethod(1);
// Output:
// Body 1
injectAtHead();
exampleObject.exampleMethod(2);
// Output:
// Head 2
// Body 2
}
public static void injectAtHead() {
// Inject methodToInject at the head of exampleObject#exampleMethod
}
public static void methodToInject(Object o) {
System.out.println("Head " + o);
}
}
After a lot of research, I came across quite a few topics that talked about dynamicly modifying bytecode with ASM. The problem is that they all talk about modifying the bytecode of a class before it is loaded by the JVM. So, I don't know how I can do this, or even if it's possible at all.
This comment pretty much answers the question.
After a few adaptations, the solution to the initial problem is: