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

这个例子用于给一个方法添加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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。