try { ClassPoolclassPool= ClassPool.getDefault(); CtClassctClass= classPool.getCtClass(className.replace("/", ".")); CtMethodmethod= ctClass.getDeclaredMethod("toString"); Stringbody="{"; body += "System.out.println(\"Change in transformer: call toString\");"; body += "return \"id: \" + id + \", name: \" + name;"; body += "}"; method.setBody(body);
CtMethodctMethod= ctClass.getDeclaredMethod("getName"); ctMethod.insertBefore("System.out.println(\"Change in transformer: Before get name\");"); ctMethod.insertAfter("System.out.println(\"Change in transformer: After get name\");");
publicclassTestAgent { publicstaticvoidmain(String[] args) { System.out.println("------------Test javaagent-------------"); TestUsertestUser=newTestUser("1", "alice"); System.out.println("get user info: " + testUser); System.out.println("get user id: " + testUser.getId()); System.out.println("get user name: " + testUser.getName()); } }
运行 javaagent
把 premain 所在类及相关类打成 jar 包,运行 TestAgent main 方法,传入 javaagent 参数,java -javaagent:xxx -jar xxx。运行结果如下
1 2 3 4 5 6 7 8 9
-------premain, args: null ------------Test javaagent------------- Change in transformer: call toString get user info: id: 1, name: alice get user id: 1 Change in transformer: Before get name get name in TestUser Change in transformer: After get name get user name: alice