KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dynaop > ClassProxyCreator


1 package dynaop;
2
3 import java.lang.reflect.Member JavaDoc;
4 import java.lang.reflect.Method JavaDoc;
5 import java.lang.reflect.Modifier JavaDoc;
6 import java.util.ArrayList JavaDoc;
7 import java.util.Arrays JavaDoc;
8 import java.util.List JavaDoc;
9
10 import dynaop.util.Classes;
11 import dynaop.util.NestedException;
12
13 import net.sf.cglib.Enhancer;
14 import net.sf.cglib.Factory;
15 import net.sf.cglib.MethodFilter;
16 import net.sf.cglib.MethodInterceptor;
17
18 /**
19  * Creates proxy instances.
20  *
21  * @author Bob Lee (crazybob@crazybob.org)
22  */

23 class ClassProxyCreator {
24
25     static final MethodFilter METHOD_FILTER = new MethodFilter() {
26         public boolean accept(Member JavaDoc m) {
27             Method JavaDoc method = (Method JavaDoc) m;
28             int modifiers = method.getModifiers();
29             
30             // skip non-public methods.
31
if (!Modifier.isPublic(modifiers))
32                 return false;
33             
34             // skip Object methods other than equals, toString, and hashCode.
35
if (method.getDeclaringClass().equals(Object JavaDoc.class) &&
36                     !Classes.OBJECT_METHODS_SET.contains(method))
37                 return false;
38             
39             return true;
40         }
41     };
42     
43     ProxyType proxyType;
44     Class JavaDoc proxyClass;
45     
46     ClassProxyCreator(ProxyType proxyType, Class JavaDoc parentClass) {
47         this.proxyType = proxyType;
48
49         Class JavaDoc[] interfaces = proxyType.getInterfaces();
50         List JavaDoc interfaceList = new ArrayList JavaDoc(interfaces.length + 1);
51
52         interfaceList.add(Proxy.class);
53         interfaceList.add(WriteReplace.class);
54         
55         interfaceList.addAll(Arrays.asList(interfaces));
56         interfaces = (Class JavaDoc[]) interfaceList.toArray(
57             new Class JavaDoc[interfaceList.size()]);
58         
59         interfaceList.add(parentClass);
60         
61         // TODO implement method filter.
62
this.proxyClass = Enhancer.enhanceClass(parentClass, interfaces,
63                 Classes.commonLoader(interfaceList), METHOD_FILTER);
64     }
65     
66     ProxyType getProxyType() {
67         return proxyType;
68     }
69
70     Proxy createProxy(MethodInterceptor handler) {
71         try {
72             Proxy proxy = (Proxy) this.proxyClass.newInstance();
73             ((Factory) proxy).interceptor(handler);
74             return proxy;
75         }
76         catch (Exception JavaDoc e) {
77             throw NestedException.wrap(e);
78         }
79     }
80     
81     public interface WriteReplace {
82         public Object JavaDoc writeReplace();
83     }
84 }
85
Popular Tags