1 8 package examples.caching; 9 10 import java.util.HashMap ; 11 import java.util.Map ; 12 13 import org.codehaus.aspectwerkz.joinpoint.JoinPoint; 14 import org.codehaus.aspectwerkz.joinpoint.MethodRtti; 15 import org.codehaus.aspectwerkz.joinpoint.Rtti; 16 17 23 public class Fibonacci { 24 25 public static int fib(int n) { 28 if (n < 2) { 29 System.err.println(n + "."); 30 return 1; 31 } else { 32 System.err.print(n + ","); 33 return fib(n - 1) + fib(n - 2); 34 } 35 } 36 37 public static void main(String [] args) { 38 System.err.println("fib(10) = " + fib(10)); 39 } 40 41 44 public static class FibonacciCacheAspect { 45 46 private Map m_cache = new HashMap (); 47 48 51 public Object cache(final JoinPoint joinPoint) throws Throwable { 52 MethodRtti mrtti = (MethodRtti) joinPoint.getRtti(); 53 Integer parameter = (Integer ) mrtti.getParameterValues()[0]; 54 Integer cachedValue = (Integer ) m_cache.get(parameter); 55 if (cachedValue == null) { 56 Object newValue = joinPoint.proceed(); m_cache.put(parameter, newValue); 58 return newValue; 59 } else { 60 System.out.println("using cache: " + cachedValue); 61 return cachedValue; } 63 } 64 } 65 } 66 67 | Popular Tags |