Java Proxies and UndeclaredThrowableException

来源:互联网 发布:打字软件手机版 编辑:程序博客网 时间:2024/05/14 20:42

Java的dynamic proxies应用广泛,尤其是在客户端/服务端架构下,客户端的调用一般都是用proxy来实现。但是,一旦proxy中的方法要抛出exception时,客户端会得到UndeclaredThrowableException,而不是真正被抛出来的exception。原因是method.invoke()只会抛出InvocationTargetException,需要手工转换成真正的exception,见下面的例子:

public class ProxyHandler implements InvocationHandler {    private InterfaceA delegate;    public ProxyHandler(InterfaceA delegate) {        this.delegate = delegate;    }    @Override        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {            System.out.println("Inside the invocation handler");            try {                return method.invoke(delegate, args);            } catch (InvocationTargetException e) {                throw e.getCause();            }        }}


参考http://amitstechblog.wordpress.com/2011/07/24/java-proxies-and-undeclaredthrowableexception/

原创粉丝点击