package huster.top;
/**
* Created by longan.rtb on 2019/7/8.
*/
public class JavaAgentTest {
public String helloWorld() {
for (int i = 0; i<5; i++) {
System.out.println("Hello world!");
}
return "ok";
}
public static void main(String[] args) {
JavaAgentTest javaAgentTest = new JavaAgentTest();
javaAgentTest.helloWorld();
}
}
Agent代码(permain方式)
package huster.top;
import java.lang.instrument.Instrumentation;
/**
* Created by longan.rtb on 2019/7/8.
*/
public class AgentMain {
public static void premain(String args, Instrumentation inst) {
System.out.println("permain has been called, arguments is : " + args);
inst.addTransformer(new AOPImplement());
}
}
public class AttachAgent {
public static void main(String[] args) throws Exception {
String pid = args[0];
String jar = args[1];
if (jar == null || "".equals(jar)) {
jar = "/Users/longan.rtb/JavaProject/javaagentdemo/originalagent/target/original-agent-jar-with-dependencies.jar";
}
VirtualMachine vmObj = null;
try {
vmObj = VirtualMachine.attach(pid);
vmObj.loadAgent(jar,
"this is arguments");
} finally {
if (vmObj != null) {
vmObj.detach();
}
}
}
}
agent的代码修改为
public class AgentMain {
public static void premain(String args, Instrumentation inst) {
System.out.println("permain has been called, arguments is : " + args);
inst.addTransformer(new AOPImplement());
}
//attach方式.
public static void agentmain(String args, Instrumentation inst){
System.out.println("444agentmain has been called, arguments is : " + args);
System.out.println("is enable :" + String.valueOf(inst.isRetransformClassesSupported()));
inst.addTransformer(new AOPImplement2(),true);
try {
inst.retransformClasses(Class.forName("huster.top.JavaAgentTest"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
坑1: 始终报UnsupportedOperationException错误
是因为我们在植入代码的时候,使用了新增函数的方法,这种方法的是不允许的在Retrans的时候
* Caused by: java.lang.UnsupportedOperationException: class redefinition failed: attempted to add a method* The retransformation may change method bodies, the constant pool and attributes.* The retransformation must not add, remove or rename fields or methods, change the* signatures of methods, or change inheritance. These restrictions maybe be* lifted in future versions. The class file bytes are not checked, verified and installed* until after the transformations have been applied, if the resultant bytes are in* error this method will throw an exception.