程序启动后启动 Java 代理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1277219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:55:14  来源:igfitidea点击:

Starting a Java agent after program start

javajavaagents

提问by Paul Keeble

Is it possible to insert a javaagent after virtual machine start from within the same VM?

是否可以在虚拟机从同一 VM 内启动后插入 javaagent?

Lets say for example we have an agent in a jar myagent.jar with the appropriate meta data set-up and an agentmain method already implemented. Now the users program calls an API call which should result in the insertion of the agent so that it can redefine the classes.

例如,我们在 jar myagent.jar 中有一个代理,具有适当的元数据设置和已经实现的 agentmain 方法。现在,用户程序调用 API 调用,这将导致插入代理,以便它可以重新定义类。

Can it be done and how?

可以做到吗?如何做到?

回答by Alan Cabrera

回答by 11101101b

Yes, you just have to pass the JVM process ID to the VirtualMachine.attach(String pid)method, and load the agent jar. The VirtualMachineclass is available in the JDK_HOME/lib/tools.jar file. Here's an example of how I activate an agent at runtime:

是的,您只需将 JVM 进程 ID 传递给该VirtualMachine.attach(String pid)方法,然后加载代理 jar。该VirtualMachine班在JDK_HOME / lib目录/文件的tools.jar可用。这是我如何在运行时激活代理的示例:

public static void attachGivenAgentToThisVM(String pathToAgentJar) {
  try {                                                                               
    String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();                                                   
    String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@'));                                                   
    VirtualMachine vm = VirtualMachine.attach(pid);                                                                            
    vm.loadAgent(pathToAgentJar, "");
    vm.detach();   
  } catch (Exception e) {
    e.printStackTrace();
  }
}                                                                                                            

回答by HerdplattenToni

You should be able to do it in Java 6, see the package documentationchapter "Starting Agents After VM Startup"

您应该可以在 Java 6 中执行此操作,请参阅包文档章节“在 VM 启动后启动代理”

edit: Maybe it was possible in Java 5 already and just the javadocs didn't mention it that explicitly

编辑:也许在 Java 5 中已经有可能了,只是 javadocs 没有明确提到它