Can I modify executed code of a static method without changing that class's code or client code? #72776
-
BodySuppose we have some Can I achieve my task? I was thinking about writing a custom // nothing of it should be modified
public class Main {
public static void main(String[] args) {
Foo.printSomething();
}
}// this code should stay intact too
public class Foo {
public static void printSomething() {
System.out.println("foo");
}
}Guidelines
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
|
To achieve your task of modifying the behavior of the Foo class without altering the client code (the Main class) or the original Foo code, you can use Java Instrumentation. Java Instrumentation allows you to modify the bytecode of classes as they are loaded by the JVM. |
Beta Was this translation helpful? Give feedback.
Here's how you can use Java Instrumentation to intercept and modify the behavior of the Foo class:
Create an agent class that implements the
java.lang.instrument.ClassFileTransformerinterface. In this class, you can redefine the Foo class.import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; import javassist.*;public class FooAgent implements ClassFileTransformer {
public static void premain(String agentArgs, Instrumentation inst) {
inst.addTransformer(new FooAgent());
}