在JDK中com.sun.tools.attach.VirtualMachine提供了一些从外部进程attach到jvm上,并执行一些操作的功能。
它提供了以下功能:
// https://github.com/xl1605368195/SimpleAgent
package com.demo;
import java.lang.instrument.Instrumentation;
public class Agent {
public static void premain(String param, Instrumentation inst) {
main(param, inst);
}
public static void agentmain(String param, Instrumentation inst) {
main(param, inst);
}
private synchronized static void main(String args, final Instrumentation inst) {
// 打印 attach时传入的参数
System.out.println("args: " + args);
}
}
import com.sun.tools.attach.*;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
VirtualMachine vm = null;
try {
vm = VirtualMachine.attach("50447");
// 指定Java Agent的jar包路径
String agentPath = "../agent-1.0-SNAPSHOT-jar-with-dependencies.jar";
vm.loadAgent(agentPath, "agent test");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
vm.detach();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}