1 package dynaop; 2 3 import java.io.Serializable ; 4 import java.lang.reflect.Method ; 5 import java.lang.reflect.UndeclaredThrowableException ; 6 7 import dynaop.util.*; 8 import dynaop.util.Classes; 9 10 28 public abstract class DispatchInterceptor implements Interceptor, 29 Serializable { 30 31 static long serialVersionUID = 0; 32 33 ThreadLocal localInvocation = new ThreadLocal (); 34 35 Cache cache = new Cache() { 36 protected Object create(Object key) { 37 try { 38 Method method = (Method ) key; 39 return DispatchInterceptor.this.getClass().getMethod( 40 method.getName(), method.getParameterTypes()); 41 } 42 catch (NoSuchMethodException e) { 43 return null; 44 } 45 } 46 }; 47 48 51 protected Invocation getInvocation() { 52 return (Invocation) localInvocation.get(); 53 } 54 55 void setInvocation(Invocation invocation) { 56 localInvocation.set(invocation); 57 } 58 59 62 protected Object proceed() throws Throwable { 63 return getInvocation().proceed(); 64 } 65 66 static boolean isInterceptMethod(Method method) { 67 Class [] types = method.getParameterTypes(); 68 return (method.getName().equals("intercept") && types != null && 69 types.length == 1 && types[0].equals(Invocation.class)); 70 } 71 72 Method getDispatchMethod(Method method) { 73 return (Method ) this.cache.get(method); 74 } 75 76 public final Object intercept(Invocation invocation) throws Throwable { 77 Method dispatch = getDispatchMethod(invocation.getMethod()); 78 if (dispatch == null) 79 return invocation.proceed(); 80 81 Invocation old = getInvocation(); 82 try { 83 setInvocation(invocation); 84 return Classes.invoke(this, dispatch, invocation.getArguments()); 85 } 86 finally { 87 setInvocation(old); 88 } 89 } 90 91 public int hashCode() { 92 try { 93 return ((Integer ) proceed()).intValue(); 94 } 95 catch (Throwable t) { 96 throw new UndeclaredThrowableException (t); 97 } 98 } 99 100 public String toString() { 101 try { 102 return (String ) proceed(); 103 } 104 catch (Throwable t) { 105 throw new UndeclaredThrowableException (t); 106 } 107 } 108 109 public boolean equals(Object o) { 110 try { 111 return ((Boolean ) proceed()).booleanValue(); 112 } 113 catch (Throwable t) { 114 throw new UndeclaredThrowableException (t); 115 } 116 } 117 118 122 public static MethodPointcut methodPointcut(final Class interceptorClass) { 123 if (!DispatchInterceptor.class.isAssignableFrom(interceptorClass)) 124 throw new ConfigurationException(interceptorClass.getName() + 125 " does not extend " + 126 DispatchInterceptor.class.getName() + "."); 127 128 return new MethodPointcut() { 129 public boolean picks(Method picked) { 130 try { 131 Method method = interceptorClass.getMethod( 132 picked.getName(), picked.getParameterTypes()); 133 134 if (method.getDeclaringClass().equals( 135 DispatchInterceptor.class)) 136 return false; 137 138 return true; 139 } 140 catch (NoSuchMethodException e) { 141 return false; 142 } 143 } 144 }; 145 } 146 } 147 | Popular Tags |