解决 Agent JAR loaded but agent failed to initialize

在使用agent进行动态替换class时遇到错误
完整错误错误信息

com.sun.tools.attach.AgentInitializationException: Agent JAR loaded but agent failed to initialize
	at sun.tools.attach.HotSpotVirtualMachine.loadAgent(HotSpotVirtualMachine.java:121)
	at com.sun.tools.attach.VirtualMachine.loadAgent(VirtualMachine.java:540)
	at com.style.note.base.instrument.Attache.main(Attache.java:18)
Disconnected from the target VM, address: '127.0.0.1:54359', transport: 'socket'

问题原因

public class CustomTransformer implements ClassFileTransformer {

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        ClassPool classPool = ClassPool.getDefault();
        try {
        	//重点 新的包名已经被修改为
        	//com.style.note.base.instrument.Base
            CtClass ctClass = classPool.get("com.style.note.base.Instrument.Base");
            CtMethod method = ctClass.getDeclaredMethod("process");
            method.insertBefore("{System.out.println(\"start\");}");
            method.insertAfter("{System.out.println(\"end \");}");
            return ctClass.toBytecode();
        } catch (NotFoundException | CannotCompileException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
 //包名错误导致加载不到class
 CtClass ctClass = classPool.get("com.style.note.base.Instrument.Base");

解决办法 更新为正确的包名 即可成功加载类

其他问题
1.MANIFEST 文件错误 检查全类名是否正确
2.agent类的方法 agentmain 一定要正确

public class Agent {
    /**
    * agentmain
    *
    * @param args  args  注意参数为String 而不是String数组
    * @param instrumentation instrumentation
    */
   public static void agentmain(String args, Instrumentation instrumentation) {
      //....
   }
}

你可能感兴趣的:(java,java,agent,agent动态替换class)