Adding an agent at runtime
suggest changeAgents 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents