Skip to content

Instantly share code, notes, and snippets.

@jordanlewis
Created February 8, 2013 20:52
Show Gist options
  • Save jordanlewis/4741829 to your computer and use it in GitHub Desktop.
Save jordanlewis/4741829 to your computer and use it in GitHub Desktop.
InvocationHandler that translates between exception types... probably not useful
static class ExceptionTranslatingForwardingInvocationHandler implements InvocationHandler {
private final ImmutableMap<Class<? extends Throwable>, Class<? extends Throwable>> exceptionMap;
private final Object delegate;
ExceptionTranslatingForwardingInvocationHandler(
Map<Class<? extends Throwable>, Class<? extends Throwable>> exceptionMap,
Object delegate) {
this.exceptionMap = ImmutableMap.copyOf(exceptionMap);
this.delegate = delegate;
}
@Override
public Object invoke(Object o, Method method, Object[] args) throws Throwable {
try {
return method.invoke(delegate, args);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
for (Class<? extends Throwable> clazz : exceptionMap.keySet()) {
if (clazz.getClass().isInstance(cause)) {
throw exceptionMap.get(clazz).newInstance();
}
}
throw cause;
} catch (IllegalAccessException e) {
// won't happen.
throw new IllegalStateException("Invocation handler caught illegal access exn.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment