使用ASM从方法中删除字节码指令

时间:2014-06-06 07:03:00

标签: java bytecode java-bytecode-asm

我一直在使用ASM在加载时动态操作类。我需要能够使用ASM删除字节码指令(即我插入的那些特定指令)。

是否有任何示例程序可以帮助我解决这个问题?

更多细节: 在第一次输入字节码期间,下面是AdviceAdapter指令。随后,在重新转换期间,我需要删除这些说明。

   protected void onMethodEnter(){
    mv.visitInsn(Opcodes.ICONST_0);
    mv.visitVarInsn(ISTORE, okFlag);

    mv.visitLdcInsn(className);
    mv.visitLdcInsn(methodName);
    mv.visitLdcInsn(description);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/agent/trace/RootTracer", "pojoMethodBegin", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z");
    mv.visitVarInsn(ISTORE, okFlag);
}

protected void onMethodExit(int opcode){
    if(opcode!=ATHROW) {
        onFinally(opcode);
    }
}

private void onFinally(int opcode){
    if(opcode == ATHROW){
        mv.visitInsn(Opcodes.DUP);
        mv.visitLdcInsn(className);
        mv.visitLdcInsn(methodName);
        mv.visitLdcInsn(description);
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/agent/trace/RootTracer", "recordException", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
    }

    mv.visitLdcInsn(className);
    mv.visitLdcInsn(methodName);
    mv.visitLdcInsn(description);
    mv.visitVarInsn(ILOAD, okFlag);
    mv.visitLdcInsn(opcode);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/agent/trace/RootTracer", "pojoMethodEnd", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZI)V");
}

0 个答案:

没有答案