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();
Output:
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)
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