KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > common > proxy > DelegateHelper


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.common.proxy;
5
6 import java.lang.reflect.Proxy JavaDoc;
7
8 /**
9  * @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 &mdash; most especially, mock-object generation for tests.
21    */

22   public static Object JavaDoc createDelegate(Class JavaDoc[] theInterfaces, Object JavaDoc delegate) {
23     return Proxy.newProxyInstance(DelegateHelper.class.getClassLoader(), theInterfaces,
24                                   new GenericInvocationHandler(delegate));
25   }
26
27   public static Object JavaDoc createDelegate(Class JavaDoc theInterface, Object JavaDoc delegate) {
28     return createDelegate(new Class JavaDoc[] { theInterface }, delegate);
29   }
30
31   /**
32    * Creates a delegate object. The object returned will be an instance of the given interfaces; by default, it will
33    * simply call through to the delegate object. However, any calls to methods of any of the interfaces that are also
34    * defined in the overrider get sent there, instead.
35    * </p>
36    * <p>
37    * Note that neither the delegate nor the overrider need comply to <em>any</em> of the given interfaces; if a method
38    * in one of the interfaces is defined in neither the handler nor the delegate, you'll get a {@link NoSuchMethodError}
39    * if you try to call it.
40    */

41   public static Object JavaDoc createDelegate(Class JavaDoc[] theInterfaces, Object JavaDoc delegate, Object JavaDoc overrider) {
42     return Proxy.newProxyInstance(DelegateHelper.class.getClassLoader(), theInterfaces,
43                                   new DelegatingInvocationHandler(delegate, overrider));
44   }
45
46   public static Object JavaDoc createDelegate(Class JavaDoc theInterface, Object JavaDoc delegate, Object JavaDoc overrider) {
47     return createDelegate(new Class JavaDoc[] { theInterface }, delegate, overrider);
48   }
49   
50 }
Popular Tags