Adding an agent at runtime
suggest changeAgents can be added to a JVM at runtime. To load an agent, use the Attach API’s VirtualMachine.attach(String id). You can then load a compiled agent JAR with the following method:
public static void loadAgent(String agentPath) {
String vmName = ManagementFactory.getRuntimeMXBean().getName();
int index = vmName.indexOf('@');
String pid = vmName.substring(0, index);
try {
File agentFile = new File(agentPath);
VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent(agentFile.getAbsolutePath(), "");
vm.detach();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
This does not call premain(String agentArgs, Instrumentation inst) in the loaded agent. It calls agentmain(String agentArgs, Instrumentation inst). That requires Agent-Class to be set in the agent manifest.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents