Instrumentation的agentmain模式

创建代理程序

项目地址

  public static void agentmain(String agentArgs, Instrumentation inst){

        inst.addTransformer(new SimClassFileTransformer(),true);

        try {
            inst.retransformClasses(Class.forName("sim.com.AgentTargetSample"));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
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("Agentmain Process by SimClassFileTransformer,target class = %s",className));

        return classfileBuffer;
    }
}

配置maven package

        
            
                org.apache.maven.plugins
                maven-jar-plugin
                3.1.2
                
                    
                        
                            
                             sim.com.AgentmainAgent
                            true
                            true
                        
                    
                
            
        

    
配置被代理程序

被代理程序项目地址

public class AgentTargetSample {

    public void sayHello(String name) {
        System.out.println(String.format("%s 我是被代理程序 通过agent模式代理!", name));
    }

    public static void main(String[] args) throws InterruptedException {
        AgentTargetSample targetSample = new AgentTargetSample();
        while (true){
            Thread.sleep(1000);
            targetSample.sayHello(Thread.currentThread().getName());
        }

    }
}

配置Attach激活程序

激活程序项目地址

   public static void main(String[] args) throws Exception {

        /**
         * 获取所有VM实例
         */
        List vmds = VirtualMachine.list();


        vmds.stream().filter(x-> x.displayName().endsWith("AgentTargetSample")).forEach(x-> {
            try {
                /**
                 * 目标VM
                 */
                VirtualMachine virtualMachine = VirtualMachine.attach(x.id());

                /**
                 * 目标VM加载Agent
                 * 参数1 代理Jar路径
                 * 参数2 命令参数
                 */
                virtualMachine.loadAgent("/Users/mac/Documents/Gitee/spring-design-pattern-demo/spring-Instrumentation-demo/java-agentmain-Instrumentation/target/java-agentmain-Instrumentation-1.0-SNAPSHOT.jar","arg1");

                virtualMachine.detach();
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }
执行顺序

1 启动被代理程序
2 启动attach激活程序

结果

Instrumentation的agentmain模式_第1张图片

你可能感兴趣的:(Instrumentation,#AgentmainAgent,JDK)