java - 如何使用 ASM 字节码框架修改 catch block 代码

标签 java java-bytecode-asm

我正在尝试更改方法内现有 try/catch block 的 catch block 的代码内容。

public static void hello(Throwable throwable) {
    try{
        System.out.println("in try");
    }catch(Exception e){
        System.out.println("in catch");
    }
}

我的意图是在 catch block 中添加一个方法调用。类似的东西,

public static void hello(Throwable throwable) {
    try{
        System.out.println("in Try");
    }catch(Exception e){
        *passException(e);*
        System.out.println("in catch");
    }
}

注意:我已经尝试覆盖 MethodVisitorvisitTryCatchBlock 方法。并尝试以多种方式访问​​标签,但无济于事。我在网上的任何文档/指南/示例中都找不到这个。我希望我已经清楚地解释了我在尝试了所有方法之后才发布这个问题。

最佳答案

如果您在 ASM 中使用 Tree API,您可以获得类的 MethodNode,然后是 MethodNode 的指令 (InsnList)。使用 InsnList 的 toArray() 方法,您可以遍历各个指令。要编辑说明,您可以这样做:

for (MethodNode method : classNode.methods) {
    method.instructions.set(insn, otherInsn); // Sets the instruction to another one
    method.instructions.remove(insn); //Removes a given instruction
    method.instructions.add(insn); //Appends to end
    method.instructions.insert(insn, otherInsn); // Inserts an instruction after the given insn
    method.instructions.insertBefore(insn, otherInsn); // Inserts an instruction before the given insn
}

我个人认为这是编辑方法体最简单的方法。

关于java - 如何使用 ASM 字节码框架修改 catch block 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36125031/

相关文章:

java - 使用注释处理器创建具有特定注释的类列表

java - 如何使用 ASM 4.0 修改 Java 字节码

java - 在asm中什么时候会调用ClassVisitor的visitMethod?

Java TextField 问题

java - 如何使用 imgscalr 将文本添加到图像

java - java中存储表格以供引用

java.lang.UnsupportedOperationException : This feature requires ASM8_EXPERIMENTAL 异常

java - 如何在 CMD 中打开程序并使用 Java 与其交互

java - 在静态中声明辅助类方法的原因是什么