创建执行类
public class PremainAgent {
//agentArgs是premain函数得到的程序参数,通过– javaagent命令行参数传入。
public static void premain(String agentArgs, Instrumentation inst){
inst.addTransformer(new SimClassFileTransformer());
}
}
实现ClassFileTransformer
public class SimClassFileTransformer implements ClassFileTransformer {
@Override
public byte[] transform(ClassLoader loader, String className,
Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
byte[] classfileBuffer) throws IllegalClassFormatException {
System.out.println(String.format("Premain Process by SimClassFileTransformer,target class = %s",className));
return classfileBuffer;
}
}
配置maven build
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<archive>
<manifestEntries>
<Premain-Class>com.sim.PremainAgent</Premain-Class>
<Can-Redefine-Classes>true</Can-Redefine-Classes>
<Can-Retransform-Classes>true</Can-Retransform-Classes>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
执行maven package,记住打包位置
创建测试程序
public class PreMainTest {
public static void main(String[] args) throws Exception{
System.out.println("PreMainTest 测试");
}
}
设置启动参数
-javaagent:xxx.xxx.jar