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

2022-06-13  本文已影响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);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读