我们先来看下这个异常类的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