01: package dynaop;
02:
03: import java.lang.reflect.Member;
04: import java.lang.reflect.Method;
05: import java.lang.reflect.Modifier;
06: import java.util.ArrayList;
07: import java.util.Arrays;
08: import java.util.List;
09:
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 m) {
27: Method method = (Method) 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.class)
36: && !Classes.OBJECT_METHODS_SET.contains(method))
37: return false;
38:
39: return true;
40: }
41: };
42:
43: ProxyType proxyType;
44: Class proxyClass;
45:
46: ClassProxyCreator(ProxyType proxyType, Class parentClass) {
47: this .proxyType = proxyType;
48:
49: Class[] interfaces = proxyType.getInterfaces();
50: List interfaceList = new ArrayList(interfaces.length + 1);
51:
52: interfaceList.add(Proxy.class);
53: interfaceList.add(WriteReplace.class);
54:
55: interfaceList.addAll(Arrays.asList(interfaces));
56: interfaces = (Class[]) interfaceList
57: .toArray(new Class[interfaceList.size()]);
58:
59: interfaceList.add(parentClass);
60:
61: // TODO implement method filter.
62: this .proxyClass = Enhancer.enhanceClass(parentClass,
63: interfaces, Classes.commonLoader(interfaceList),
64: METHOD_FILTER);
65: }
66:
67: ProxyType getProxyType() {
68: return proxyType;
69: }
70:
71: Proxy createProxy(MethodInterceptor handler) {
72: try {
73: Proxy proxy = (Proxy) this .proxyClass.newInstance();
74: ((Factory) proxy).interceptor(handler);
75: return proxy;
76: } catch (Exception e) {
77: throw NestedException.wrap(e);
78: }
79: }
80:
81: public interface WriteReplace {
82: public Object writeReplace();
83: }
84: }
|