动态代理和检查的异常 [英] Dynamic proxy and checked exceptions

查看:98
本文介绍了动态代理和检查的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使我的动态代理抛出已检查的异常?

How can I make my dynamic proxy throw checked exceptions?

我需要一个透明的包装器来包装某个接口,该包装器有时会抛出诸如IOException之类的已检查异常.如果没有第三方AOP或编写我自己的代理,是否可以?也不可以手动修改接口的所有20种方法.

I need a transparent wrapper for an interface which sometimes throws checked exceptions such as IOException. Is it possible without 3rd party AOP or writing my own proxy? Modifying all 20 methods of the interface by hand is not an option either.

推荐答案

您可以使用动态代理.只要已检查的异常是接口的一部分,您就可以从调用处理程序中抛出已检查的异常.否则,这将是非法的,并会创建一个UndeclaredThrowableException来包装引发的检查异常.

You can use a dynamic proxy. As long as the checked exceptions are part of the interface you can throw the checked exceptions from the invocation handler. Otherwise this is illegal and will create an UndeclaredThrowableException that wraps the thrown checked exception.

interface A{
    void x() throws IOException;
}

A proxy = (A) newProxyInstance(classLoader, new Class<?>[]{A.class}, 
  new InvocationHandler() {      
        @Override
        public Object invoke(Object arg0, Method arg1, Object[] arg2) 
            throws Throwable {
            throw new IOException();
        }
   }
);
proxy.x();

输出:

Exception in thread "main" java.io.IOException
at X$1.invoke(X.java:19)
at $Proxy0.x(Unknown Source)
at X.main(X.java:22)

具有接口A的未声明的检查异常:

With an undeclared checked exception for interface A:

interface A{
    void x();
}

Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
  at $Proxy0.x(Unknown Source)
  at X.main(X.java:22)
Caused by: java.io.IOException
  at X$1.invoke(X.java:19)
  ... 2 more

这篇关于动态代理和检查的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆