01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.common.proxy;
05:
06: import com.tc.logging.TCLogger;
07: import com.tc.logging.TCLogging;
08: import com.tc.util.Assert;
09:
10: import java.lang.reflect.InvocationTargetException;
11: import java.lang.reflect.Method;
12:
13: /**
14: * @author andrew A {@link GenericInvocationHandler}that delegates all unknown methods to a special 'delegate' object.
15: * This is very useful for creating delegates that override only certain methods.
16: */
17: class DelegatingInvocationHandler extends GenericInvocationHandler {
18: private static final TCLogger logger = TCLogging
19: .getLogger(GenericInvocationHandler.class);
20: private final Object delegate;
21:
22: public DelegatingInvocationHandler(Object delegate, Object handler) {
23: super (handler);
24: Assert.eval(delegate != null);
25: this .delegate = delegate;
26: }
27:
28: protected Object handlerMethodNotFound(Object proxy, Method method,
29: Object[] args) throws Throwable {
30: try {
31: Method theMethod = delegate.getClass().getMethod(
32: method.getName(), method.getParameterTypes());
33:
34: try {
35: theMethod.setAccessible(true);
36: } catch (SecurityException se) {
37: logger.warn("Cannot setAccessible(true) for method ["
38: + theMethod + "], " + se.getMessage());
39: }
40:
41: return theMethod.invoke(delegate, args);
42: } catch (InvocationTargetException ite) {
43: // We need to unwrap this; we want to throw what the method actually
44: // threw, not an InvocationTargetException (which causes all sorts of
45: // madness, since it's unlikely the interface method throws that
46: // exception, and you'll end up with an UndeclaredThrowableException.
47: // Blech.)
48: throw ite.getCause();
49: } catch (NoSuchMethodException nsme) {
50: return super.handlerMethodNotFound(proxy, method, args);
51: }
52: }
53: }
|