Java Language Java Agents Adding an agent at runtime

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Agents can be added to a JVM at runtime. To load an agent you will need to use the Attach API's VirtualMachine.attatch(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(), "");
        VirtualMachine.attach(vm.id());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

This will not call premain((String agentArgs, Instrumentation inst) in the loaded agent, but instead will call agentmain(String agentArgs, Instrumentation inst). This requires Agent-Class to be set in the agent Manifest.mf.



Got any Java Language Question?