1.首先启动一个tomcat,jps查看进程。
image.png
2.编写agent并打包。
package agent;
import java.lang.instrument.Instrumentation;
/**
* @author qishaojun
*/
public class TestAgent {
// public static void premain(String agentArgs, Instrumentation inst) {
// System.out.println("premain start ...");
// System.out.println(agentArgs);
// }
public static void agentmain(String args, Instrumentation inst) {
System.out.println("loadagent after main run.args=" + args);
Class>[] classes = inst.getAllLoadedClasses();
for (Class> cls : classes) {
System.out.println(cls.getName());
}
System.out.println("agent run completely");
}
}
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
sjqi.test
agent
1.0-SNAPSHOT
jar
org.apache.maven.plugins
maven-jar-plugin
2.3.1
true
agent.TestAgent
maven 配置是为了确保jar包打出来的MANIFEST.MF是这样的
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: MC
Build-Jdk: 1.8.0_191
Agent-Class: agent.TestAgent
3.编写操纵程序
//maven引入
com.sun
tools
1.8.0
system
C:/Program Files/Java/jdk1.8.0_191/lib/tools.jar
//代码编写
package com.sprucetec.pop;
import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import java.io.IOException;
/**
* @author qishaojun
*/
public class TestAgent {
public static void main(String[] args) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
VirtualMachine vm=VirtualMachine.attach("2192");
vm.loadAgent("D:/pop-space/agent/target/agent-1.0-SNAPSHOT.jar");
}
}
4.运行效果在tomcat的控制台
image.png