然后实现ClassFileTransformer接口,ClassFileTransform用于类的转换,其接口transform是转换类的关键,其第四个入参也是我们后续修改字节码的关键:
public class ClassTransformerImpl implements ClassFileTransformer { @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { System.out.println("类的名字为:" + className); return classfileBuffer; }}复制代码上面再transform中我们打印了所有类的名字,回到我们的premain中我们的方法如下:
public class PerfMonAgent { static private Instrumentation inst = null; public static void premain(String agentArgs, Instrumentation _inst) { System.out.println("PerfMonAgent.premain() was called."); // Initialize the static variables we use to track information. inst = _inst; // Set up the class-file transformer. ClassFileTransformer trans = new ClassTransformerImpl(); System.out.println("Adding a PerfMonXformer instance to the JVM."); //将我们自定义的类转换器传入进去 inst.addTransformer(trans); }}复制代码我们可以把上面的premain方法修改如下:
public class PerfMonAgent { static private Instrumentation inst = null; public static void premain(String agentArgs, Instrumentation _inst) { System.out.println("PerfMonAgent.premain() was called."); // Initialize the static variables we use to track information. inst = _inst; // Set up the class-file transformer. ClassFileTransformer trans = new ClassTransformerImpl(); System.out.println("Adding a PerfMonXformer instance to the JVM."); //将我们自定义的类转换器传入进去 inst.addTransformer(trans); }}复制代码代码方面的已经定义完毕。接下来需要将其进行打包如果你没用Maven那么你需要在其中的 manifest 属性当中加入” Premain-Class”来指定当中编写的那个带有 premain 的 Java 类。如果你是使用的maven那么你可以用
<plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.2</version> <configuration> <archive> <manifestEntries> <Premain-Class>instrument.PerfMonAgent</Premain-Class> //这个是用来引入第三方包,需要在这里引入 <Boot-Class-Path>/Users/lizhao/.m2/repository/org/ow2/asm/asm/5.0.4/asm-5.0.4.jar</Boot-Class-Path> </manifestEntries> </archive> </configuration> </plugin></plugins>复制代码最后你可以使用了,你随意编写一个带main方法的类:
java -javaagent:jar 文件的位置 [= 传入 premain 的参数 ] 复制代码如果是idea编译器你可以在vm配置中输入