1 package groovy.lang; 2 3 import org.codehaus.groovy.runtime.InvokerHelper; 4 5 import java.beans.IntrospectionException ; 6 7 15 public class ProxyMetaClass extends MetaClass { 16 17 protected MetaClass adaptee = null; 18 protected Interceptor interceptor = null; 19 20 23 public static ProxyMetaClass getInstance(Class theClass) throws IntrospectionException { 24 MetaClassRegistry metaRegistry = InvokerHelper.getInstance().getMetaRegistry(); 25 MetaClass meta = metaRegistry.getMetaClass(theClass); 26 return new ProxyMetaClass(metaRegistry, theClass, meta); 27 } 28 31 public ProxyMetaClass(MetaClassRegistry registry, Class theClass, MetaClass adaptee) throws IntrospectionException { 32 super(registry, theClass); 33 this.adaptee = adaptee; 34 if (null == adaptee) throw new IllegalArgumentException ("adaptee must not be null"); 35 } 36 37 40 public void register() { 41 registry.setMetaClass(theClass, this); 42 } 43 44 47 public void unRegister() { 48 registry.setMetaClass(theClass, adaptee); 49 } 50 51 54 public Interceptor getInterceptor() { 55 return interceptor; 56 } 57 58 61 public void setInterceptor(Interceptor interceptor) { 62 this.interceptor = interceptor; 63 } 64 65 71 public Object invokeMethod(final Object object, final String methodName, final Object [] arguments) { 72 return doCall(object, methodName, arguments, new Callable(){ 73 public Object call() { 74 return adaptee.invokeMethod(object, methodName, arguments); 75 } 76 }); 77 } 78 84 public Object invokeStaticMethod(final Object object, final String methodName, final Object [] arguments) { 85 return doCall(object, methodName, arguments, new Callable(){ 86 public Object call() { 87 return adaptee.invokeStaticMethod(object, methodName, arguments); 88 } 89 }); 90 } 91 92 98 public Object invokeConstructor(final Object [] arguments) { 99 return doCall(theClass, "ctor", arguments, new Callable(){ 100 public Object call() { 101 return adaptee.invokeConstructor(arguments); 102 } 103 }); 104 } 105 106 private interface Callable{ 108 Object call(); 109 } 110 private Object doCall(Object object, String methodName, Object [] arguments, Callable howToInvoke) { 111 if (null == interceptor) { 112 return howToInvoke.call(); 113 } 114 Object result = interceptor.beforeInvoke(object, methodName, arguments); 115 if (interceptor.doInvoke()) { 116 result = howToInvoke.call(); 117 } 118 result = interceptor.afterInvoke(object, methodName, arguments, result); 119 return result; 120 } 121 } 122 | Popular Tags |