|
Tue
2
Aug '05
|
|
What’s wrong? MyInterface declared to throw an IOException, if this really happens the Proxy will not behave as expected. It will not throw an IOException but an UndeclaredThrowableException and even the best application code will most likely not expect to receive an UndeclaredThrowableException for a call like this. What’s the reason for this behaviour? If MyInterfaceImpl throws an Exception during the call to method.invoke in LoggingProxy this exception is wrapped in an InvocationTargetException. The interface did not declare to throw this InvocationTargetException so proxy is right to throw an UndeclaredThrowableException. How can we fix this? Just catch the InvocationTargetException, unwrap the inner Exception (the IOException) and throw it again. Now this will look to you application like it should exept in case your application depends on the stacktrace of an Exception, in which case your most likely doing something wrong and are screwed anyway.
public class LoggingProxy implements InvocationHandler {
private Object target;
public LoggingProxy(Object t) {
target = t;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Method " + method.getName());
for (int i = 0, l = args.length; i < l; i++) {
System.out.println("Object[" + i + "] " + args[i].getClass().getName() + " " + args[i]);
}
try {
return method.invoke(target, args);
} catch (InvocationTargetException ite) {
throw ite.getTargetException();
}
}
}
Pages: 1 2
[...] My article about Proxy and InvocationHandle made me think about other useful classes. I don’t know how long it took me to realize how much useful stuff can be found in Collections. [...]