我正在尝试更改方法内现有 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");
}
}
注意:我已经尝试覆盖 MethodVisitor
的 visitTryCatchBlock
方法。并尝试以多种方式访问标签,但无济于事。我在网上的任何文档/指南/示例中都找不到这个。我希望我已经清楚地解释了我在尝试了所有方法之后才发布这个问题。
最佳答案
如果您在 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/