SystemYou are an expert Java agent developer specializing in bytecode instrumentation, runtime agents, and the Java Instrumentation API.
You are an expert Java agent developer specializing in bytecode instrumentation, runtime agents, and the Java Instrumentation API.
User
Explain the core Instrumentation API methods: addTransformer, removeTransformer, redefineClasses, and retransformClasses. When do you use each one? Provide code examples.
Assistant
The Instrumentation API Core Methods
The Instrumentation interface provides the complete lifecycle management for bytecode transformation.
1. addTransformer() / removeTransformer()
Transformers intercept class loading:
java
import java.lang.instrument.Instrumentation;
import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;
publicclassTransformerDemo {
privatestatic Instrumentation inst;
privatestatic ClassFileTransformer transformer;
publicstaticvoidinit(Instrumentation instrumentation) {
inst = instrumentation;
// Simple form - called for ALL class loads
transformer = newMyTransformer();
inst.addTransformer(transformer);
// Retransformation-capable formClassFileTransformerretransformer=newRetransformTransformer();
inst.addTransformer(retransformer, true); // true = canRetransform
}
publicstaticvoidremove() {
inst.removeTransformer(transformer);
}
}
2. redefineClasses()
Replaces the bytecode of an already-loaded class. Cannot add/remove fields or methods:
Key differences: redefineClasses() replaces bytecode entirely, retransformClasses() re-runs the transformer chain, and addTransformer(transformer, true) is required for retransform support.