1、模式一:-javaaent
1.1、编写 MyAgent.java
import java.lang.instrument.Instrumentation;
public class MyAgent {
public static void premain(String agentArg, Instrumentation instrumentation) {
System.out.println("premain");
}
}
1.2、在META-INF文件夹创建 MANIFEST.MF 文件
Premain-Class: MyAgent 下面要有一行空行
Manifest-Version: 1.0
Premain-Class: MyAgent
1.3、 编译MyAgent.java
javac MyAgent.java
1.4、打包xx.jar
jar cfm xx.jar ./META-INF/MANIFEST.MF MyAgent.class
1.5、创建一个含有main函数的类
public class A {
public static void main(String[] args) throws InterruptedException {
int i = 0;
while (true) {
print(i++);
Thread.sleep(1000);
}
}
private static void print(Object obj) {
System.out.println(obj);
}
}
1.6、编译A.java
javac A.java
1.7、运行
-javaagent:D:/study/myAgent/xx.jar一定要写在A.class之前
java -javaagent:D:/study/myAgent/xx.jar A