动态代理模式下UndeclaredThrowableException的产生

API文档

我们先来看下这个异常类的api文档:

Thrown by a method invocation on a proxy instance if its invocation handler’s invoke method throws a checked exception (a Throwable that is not assignable to RuntimeException or Error) that is not assignable to any of the exception types declared in the throws clause of the method that was invoked on the proxy instance and dispatched to the invocation handler.

这段描述中介绍了异常会被抛出的情况:调用代理实例的增强方法,如果调用处理程序(增强器)的invoke方法中抛出一个检查异常,但该异常不能被throws子句中声明的任何异常捕获(默认是RuntimeException和Error),那么UndeclaredThrowableException这个异常就会被代理实例抛出。

代码演示

由于是使用JDK的动态代理进行演示,那肯定少不了接口类:

public interface Animal {
    // 奔跑
    void run();
}
复制代码

被代理类:

public class Pig implements Animal {
    @Override
    public void run() {
        System.out.println("猪突猛进");
    }
}
复制代码

以及增强器InvocationHandler

public class AnimalInvocationHandler implements InvocationHandler {

    private final Object target;

    public AnimalInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("增强方法 -> className: " + target.getClass().getSimpleName() + " methodName:" + method.getName());
        method.invoke(target, args);
        throw new E
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值