Adding an agent at runtime

suggest change

Agents 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents