Build a Java Agent with Instrumentation
A Java agent can observe or transform classes as the JVM loads them. Startup agents enter through premain; agents attached to a running JVM enter through agentmain.
public final class Agent {
public static void premain(String args, Instrumentation inst) {
inst.addTransformer(new LoggingTransformer(), true);
}
public static void agentmain(String args, Instrumentation inst) {
inst.addTransformer(new LoggingTransformer(), true);
}
}
The agent JAR manifest must declare the appropriate entry point:
Premain-Class: example.Agent
Agent-Class: example.Agent
Can-Redefine-Classes: true
Can-Retransform-Classes: true
A ClassFileTransformer receives raw class bytes and may return modified bytes. Do not instrument the agent itself or core classes unintentionally, and keep transformation code deterministic and fast.
Bytecode changes must preserve verifier rules, stack maps, method semantics, and compatibility with the target Java version. Libraries such as Byte Buddy or ASM are safer than editing class bytes manually. Agents run with powerful in-process access, so protect attach permissions and treat agent code as production-critical infrastructure.