//實現ClassFileTransformer 接口 package com.baobaotao.instrument; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; public class Transformer implements ClassFileTransformer { @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { System.out.println("=========================hello world"+className); return null; } }
package com.baobaotao.instrument; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; public class Agent { public static void premain(String agentArgs, Instrumentation inst){ ClassFileTransformer cft = new Transformer();//實例化轉換器 inst.addTransformer(cft);//將轉換器註冊到JVM中的Instrumentation 中 } }
//定義一個main主類,做爲程序的入口 package com.baobaotao.instrument; public class Test { public static void main(String[] args) { System.out.println("I'm in main() of Test..."); } }
手工編寫一個清單文件myManifest.mf(放到工做目錄src下)java
Manifest-Version: 1.0 Premain-Class: com.baobaotao.instrument.Agent
在eclipse中,經過Export...操做將com.baobaotao.instrument包中的類打成一個JAR包。shell
將生成的jar包放到cmd的運行目錄(C:\Users\lenovo)下執行eclipse
C:\Users\lenovo>java -javaagent:my.jar com.baobaotao.instrument.Test =========================hello worldcom/baobaotao/instrument/Test I'm in main() of Test... C:\Users\lenovo>