InvocationTargetException与UndeclaredThrowableException

InvocationTargetException

当java反射调用方抛出异常时,就会用InvocationTargetException将原异常包裹;

UndeclaredThrowableException

java动态代理时抛出的异常。当对某接口进行动态代理,接口的方法名称上未声明某类受检异常,而方法却抛出了该异常,动态代理会将该异常用UndeclaredThrowableException包裹。

由于jdk动态代理内部会调用method.invoke进行调用,当method抛出异常时,则会抛出InvocationTargetException。

由于InvocationTargetException是受检异常,当代理接口方法未标识InvocationTargetException,则抛出UndeclaredThrowableException

处理方法:

public static Throwable unwrapThrowable(Throwable wrapped) {
Throwable unwrapped = wrapped;
while (true) {
if (unwrapped instanceof InvocationTargetException) {
unwrapped = ((InvocationTargetException) unwrapped).getTargetException();
} else if (unwrapped instanceof UndeclaredThrowableException) {
unwrapped = ((UndeclaredThrowableException) unwrapped).getUndeclaredThrowable();
} else {
return unwrapped;
}
}
}
posted @ 2017-12-19 15:10  三美元  阅读(1768)  评论(0编辑  收藏  举报