Java agents are pluggable self contained components that run embedded in a JVM and intercept the classloading process. They were introduced in Java 5 along with the powerful java.lang.instrument package. Java agents can be loaded statically at startup or dynamically (programmatically) at runtime to attach to a running process.
Java agents were an awesome addition to the JVM as it opened a lot of opportunities for tool designers and changed Java tooling landscape quite drastically. In conjunction with Java bytecode manipulation libraries it is now possible to do amazing things to Java classes: we can experiment with programming models, redefine classes at runtime, record execution flow, etc.
I’d like to give an overview of Java agents’ functionality along with the usage examples and real world experiences. You will learn, how to implement an agent and apply Instrumentation API in combination with bytecode manipulation libraries to solve interesting tasks.
36. • Executed when the agent attaches to the running JVM
• Instrumentation parameter is optional
• META-INF/MANIFEST.MF is required
• Requires support for loading agents in JVM
• Allows adding the code to JVM post-factum
public static void agentmain(String args,
Instrumentation inst)
37. import com.sun.tools.attach.VirtualMachine;
//attach to target VM
VirtualMachine vm = VirtualMachine.attach("2177");
//get system properties in the target VM
Properties props = vm.getSystemProperties();
//load agent into the VM
vm.loadAgent("agent.jar", "arg1=x,arg2=y");
//detach from VM
vm.detach();
http://docs.oracle.com/javase/7/docs/jdk/api/attach/spec/com/sun/tools/attach/VirtualMachine.html