可以在运行时将代理添加到JVM。要加载代理,您将需要使用Attach API的。然后,您可以使用以下方法加载已编译的代理jar:VirtualMachine.attatch(String id)
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);
}
}这不会在已加载的代理中调用premain((String agentArgs,Instrumentation inst),而是会调用agentmain(String agentArgs, Instrumentation inst)。这需要在代理Manifest.mf中设置Agent-Class。