1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.composite.util;
17
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21
22 /***
23 * An invocation handler that delegates method calls to a delegate object. This
24 * invocation handler is useful for declaring that a class implements a given
25 * interface at runtime rather than at compile time. The delegate object must
26 * already have implementations for each method declared in the interface.
27 *
28 * @author Matt Sgarlata
29 * @since Dec 27, 2004
30 */
31 public class DelegatingInvocationHandler implements InvocationHandler {
32
33 private Object delegate;
34
35 /***
36 * Creates a new invocation handler that delegates invocation requests to
37 * the specified delegate.
38 *
39 * @param delegate
40 * the delegate that will be used
41 */
42 public DelegatingInvocationHandler(Object delegate) {
43 super();
44 setDelegate(delegate);
45 }
46
47 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
48 try {
49 Object delegateToUse = getDelegate(proxy, method, args);
50 Method delegateMethod = getDelegateMethod(delegateToUse, method, args);
51 return delegateMethod.invoke(delegateToUse, args);
52 }
53
54
55 catch (InvocationTargetException e) {
56 throw e.getTargetException();
57 }
58 }
59
60 protected Method getDelegateMethod(Object delegate, Method method, Object[] args)
61 throws Exception {
62 return delegate.getClass().getMethod(method.getName(), method.getParameterTypes());
63 }
64
65 protected Object getDelegate(Object proxy, Method method, Object[] args) {
66 return getDelegate();
67 }
68
69 public Object getDelegate() {
70 return delegate;
71 }
72
73 public void setDelegate(Object delegate) {
74 this.delegate = delegate;
75 }
76
77 }