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 java.lang.reflect.Proxy;
07:
08: /**
09: * @author andrew A helper for easily creating overridden delegates for classes.
10: */
11: public class DelegateHelper {
12:
13: /**
14: * Creates a delegate object. The object returned will be an instance of the given interfaces. Any calls to the
15: * returned object will simply call through to the passed-in delegate.
16: * </p>
17: * <p>
18: * So why use this method? Well, delegate does <em>not</em> have to implement <em>any</em> of the given interface.
19: * Any methods on the interface that are not implemented in the delegate will simply throw a {@link NoSuchMethodError}
20: * if called. This is useful for many things — most especially, mock-object generation for tests.
21: */
22: public static Object createDelegate(Class[] theInterfaces,
23: Object delegate) {
24: return Proxy.newProxyInstance(DelegateHelper.class
25: .getClassLoader(), theInterfaces,
26: new GenericInvocationHandler(delegate));
27: }
28:
29: public static Object createDelegate(Class theInterface,
30: Object delegate) {
31: return createDelegate(new Class[] { theInterface }, delegate);
32: }
33:
34: /**
35: * Creates a delegate object. The object returned will be an instance of the given interfaces; by default, it will
36: * simply call through to the delegate object. However, any calls to methods of any of the interfaces that are also
37: * defined in the overrider get sent there, instead.
38: * </p>
39: * <p>
40: * Note that neither the delegate nor the overrider need comply to <em>any</em> of the given interfaces; if a method
41: * in one of the interfaces is defined in neither the handler nor the delegate, you'll get a {@link NoSuchMethodError}
42: * if you try to call it.
43: */
44: public static Object createDelegate(Class[] theInterfaces,
45: Object delegate, Object overrider) {
46: return Proxy.newProxyInstance(DelegateHelper.class
47: .getClassLoader(), theInterfaces,
48: new DelegatingInvocationHandler(delegate, overrider));
49: }
50:
51: public static Object createDelegate(Class theInterface,
52: Object delegate, Object overrider) {
53: return createDelegate(new Class[] { theInterface }, delegate,
54: overrider);
55: }
56:
57: }
|