美文网首页
使用ASM给一个方法添加try catch块

使用ASM给一个方法添加try catch块

作者: 大冷月 | 来源:发表于2022-06-13 22:04 被阅读0次

这个例子用于给一个方法添加try catch

public class MoonTryCatchMethodVisitor extends AdviceAdapter {

    private final Label start = new Label();
    private final Label end = new Label();
    private final Label catchLabel = new Label();
    private final Type returnType;

    public MoonTryCatchMethodVisitor(MethodVisitor methodVisitor, final int access,
                                     final String name,
                                     final String descriptor) {
        super(Opcodes.ASM6, methodVisitor, access, name, descriptor);
        returnType = Type.getReturnType(descriptor);
    }

    @Override
    protected void onMethodEnter() {
        super.onMethodEnter();
        visitLabel(start);
        visitTryCatchBlock(start, end, catchLabel, "java/lang/Exception");
    }

    @Override
    public void visitMaxs(final int maxStack, final int maxLocals) {
        mv.visitLabel(end);
        mv.visitLabel(catchLabel);
        mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{"java/lang/Exception"});
        int local = newLocal(Type.LONG_TYPE);
        mv.visitVarInsn(ASTORE, local);
        mv.visitVarInsn(ALOAD, local);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Exception", "printStackTrace", "()V", false);

        //根据返回值类型,添加一条返回语句
        if (returnType.equals(Type.getType(String.class))) {
            mv.visitLdcInsn("");//返回一个空字符串
        } else if (returnType.equals(Type.getType(byte.class)) || returnType.equals(Type.getType(short.class))
                || returnType.equals(Type.getType(int.class)) || returnType.equals(Type.getType(long.class))
                || returnType.equals(Type.getType(float.class)) || returnType.equals(Type.getType(double.class))) {
            mv.visitLdcInsn(11);//返回一个默认数值
        }
        mv.visitInsn(Opcodes.ARETURN);
        super.visitMaxs(maxStack, nextLocal);
    }
}

相关文章

  • 使用ASM给一个方法添加try catch块

    这个例子用于给一个方法添加try catch

  • ASM给方法加try catch

    期望通过注解的形式,给方法套上try catch。老样子,先看一下try catch的字节码。 CatchUtil...

  • JS错误处理

    1、使用try catch语句 如果 try 块中有代码发生错误,代码会立即退出执行,并跳到 catch 块中。错...

  • Kotlin异常处理(2)捕获异常

    try-catch 语句try-catch 表达式多 catch 代码块try-catch 语句嵌套 一、try-...

  • try catch捕获异常

    try/catch主要用于捕获异常,try/catch语句包含了yigebtry块,和至少有一个catch块或者饿...

  • 错误处理

    try ... catch ... finally JavaScript 使用 try ... catch ......

  • javase part19 异常

    使用try-catch-finally 语句块处理一场 在方法中使用throw 关键字 手动抛出异常,在方法声明处...

  • C++语法系列之9-- 异常处理

    1 异常常识: 1)使用throw抛出异常;2)使用try-catch 语句块捕获异常;3)catch语句块中,可...

  • Android Transform+ASM添加try catch

    Transform这个部分这里不作讲解,直接使用hunter库就行,里面对Transform遍历处理class文件...

  • 异常处理

    try-catch-finally 语法格式: try块:用于捕获异常catch块:用于处理try捕获到的异常fi...

网友评论

      本文标题:使用ASM给一个方法添加try catch块

      本文链接:https://www.haomeiwen.com/subject/gulamrtx.html