01: package org.mockejb.interceptor;
02:
03: import java.lang.reflect.Method;
04:
05: import net.sf.cglib.proxy.*;
06:
07: /**
08: * Creates dynamic proxy and acts as an InvocationHandler for
09: * this proxy. During invocation, obtains relevant interceptors from
10: * AspectSystem and makes them part of the invocation chain.
11: * Uses Cglib internally.
12: *
13: * Use this class when you have an interface/class and a single implementation class
14: * for this interface.
15: * Usage example:
16: * <code>(Context) InterceptableProxy.create(
17: * Context.class, new MockContext() );
18: * </code>
19: *
20: * You can also create proxies for classes (including using the same class
21: * as the intercepted and target class) :
22: * <code>
23: * InterceptableTestClass proxy = (InterceptableTestClass)
24: * InterceptableProxy.create( TestImpl.class, new TestImpl() );
25: * </code>
26: * Note that implementation classes don't have to be public (cglib feature).
27: *
28: * @author Alexander Ananiev
29: */
30: public class InterceptableProxy implements MethodInterceptor {
31:
32: private Class ifaceClass;
33: private Object implObj;
34:
35: private InterceptorInvoker interceptorInvoker = new InterceptorInvoker();
36:
37: public static Object create(Class ifaceClass, Object implObj) {
38: Enhancer e = new Enhancer();
39: e.setSuperclass(ifaceClass);
40:
41: e.setCallback(new InterceptableProxy(ifaceClass, implObj));
42:
43: return e.create();
44:
45: }
46:
47: InterceptableProxy(Class ifaceClass, Object implObj) {
48: this .ifaceClass = ifaceClass;
49: this .implObj = implObj;
50: }
51:
52: public Object intercept(Object obj, Method proxyMethod,
53: Object[] paramVals, MethodProxy proxy) throws Throwable {
54:
55: Method implMethod = implObj.getClass().getMethod(
56: proxyMethod.getName(), proxyMethod.getParameterTypes());
57:
58: return interceptorInvoker.invoke(obj, proxyMethod, implObj,
59: implMethod, paramVals);
60:
61: }
62:
63: }
|