Starting a Java agent after program start

后端 未结 4 1205
野性不改
野性不改 2020-12-05 03:11

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

Lets say for example we have an agent in a jar myagent.jar with the appropr

4条回答
  •  清歌不尽
    2020-12-05 03:43

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

    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();
      }
    }                                                                                                            
    

提交回复
热议问题