我发现Java附加API可以按以下代码加载javaagent:
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import java.util.List;
public class ListVM{
public static void main(String[] args){
List<VirtualMachineDescriptor> vmList = VirtualMachine.list();
for(VirtualMachineDescriptor vm : vmList){
System.out.println("name: " + vm.displayName() + " id :" + vm.id());
try{
VirtualMachine vm0 = VirtualMachine.attach(vm.id());
// load agent, agnet class's agentmain will be invoked.
vm0.loadAgent("/root/tmp/ChinaAgent.jar");
System.out.println("Load agent done.");
vm0.detach();
}catch(Exception e) {
System.out.println("exception : " + e.getMessage());
}
}
}
}语句:vm0.loadAgent("/root/tmp/ChinaAgent.jar");,它加载代理jar文件。
但特工的代码只能运行一次,
因此,我猜代理jar只加载了一次,这意味着Jvm防止多次加载代理。
这是事实吗?为什么?
希望能有一些代码来证明这一点!
谢谢!
发布于 2014-10-09 11:27:19
当您调用loadAgent时,代理jar只运行一次。调用JAR清单中由agentmain属性指定的代理类的Agent-Class方法。
类实际上只加载一次,除非您已经完成了一些优化来卸载类。因此,如果在同一个jar上多次调用loadAgent,类将不会被重新加载,但是Agent_OnAttach (agentmain)可能会被多次调用。实际上,它是特定于平台的,并且依赖于JVM实现。
loadAgent方法调用loadAgentLibrary,它调用特定于平台的Agent_OnAttach
参考资料:
jdk\src\windows\native\sun\tools\attach\WindowsVirtualMachine.c文件。https://stackoverflow.com/questions/26275503
复制相似问题