解决方法
您可以使用动态代理.只要检查的异常是接口的一部分,您可以从调用处理程序中抛出检查的异常.否则,这是非法的,并将创建一个UndeclaredThrowableException来包装抛出的检查的异常.
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,未经声明的检查异常:
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