|
Code Listing 2: The CachingInterceptor class
import dynaop.Interceptor;
import dynaop.Invocation;
import java.lang.Package;
import java.lang.reflect.Method;
import java.util.HashMap;
public class CachingInterceptor implements Interceptor
{
private HashMap cacheMap = new HashMap();
public Object intercept(Invocation invocation)
throws Throwable
{
Long cacheCode = calculateCacheCode(invocation);
// Look for method result in cache.
Object cachedResult = cacheMap.get(cacheCode);
if (cachedResult != null)
{
// Log cache hit.
String methodName = getFullMethodName(invocation);
System.out.println("Returning cached result for: " + methodName);
return cachedResult;
}
// Call intercepted method and cache its result.
Object result = invocation.proceed();
cacheMap.put(cacheCode, result);
return result;
}
private Long calculateCacheCode(Invocation invocation)
{
return new Long(getFullMethodName(invocation).hashCode());
}
private static String getFullMethodName(Invocation invocation)
{
Method method = invocation.getMethod();
StringBuffer methodName = new StringBuffer();
// Add package name.
Package pkg = method.getDeclaringClass().getPackage();
if (pkg != null) {
methodName.append(pkg.getName() + ".");
}
// Add class name.
methodName.append(method.getDeclaringClass().getName());
// Add method name.
methodName.append("." + method.getName());
// Add argument names.
methodName.append("(");
Class[] arguments = method.getParameterTypes();
for (int i = 0; i < arguments.length; i++) {
if (i > 0) {
methodName.append(",");
}
methodName.append(arguments[i].getName());
}
methodName.append(")");
return methodName.toString();
}
}
|