1 package org.shiftone.cache.util; 2 3 4 5 import org.shiftone.cache.Cache; 6 7 import java.lang.reflect.InvocationHandler ; 8 import java.lang.reflect.Method ; 9 import java.lang.reflect.UndeclaredThrowableException ; 10 import java.util.Arrays ; 11 12 13 21 public class CacheInvocationHandler implements InvocationHandler  22 { 23 24 private Cache cache = null; 25 private Object target = null; 26 27 public CacheInvocationHandler(Object target, Cache cache) 28 { 29 this.cache = cache; 30 this.target = target; 31 } 32 33 34 public Object invoke(Object proxy, Method method, Object [] args) throws Throwable  35 { 36 37 Object result = null; 38 Throwable throwable = null; 39 CallKey callKey = null; 40 41 callKey = new CallKey(method.getName(), args); 42 43 try 44 { 45 result = cache.getObject(callKey); 46 47 if (result == null) 48 { 49 result = method.invoke(target, args); 50 51 cache.addObject(callKey, result); 52 } 53 } 54 catch (UndeclaredThrowableException e) 55 { 56 throw e.getUndeclaredThrowable(); 57 } 58 59 return result; 60 } 61 } 62 63 class CallKey 64 { 65 66 private final String methodName; 67 private final Object [] args; 68 69 public CallKey(String methodName, Object [] args) 70 { 71 this.methodName = methodName; 72 this.args = args; 73 } 74 75 76 public int hashCode() 77 { 78 79 int code = methodName.hashCode(); 80 81 if (args != null) 82 { 83 for (int i = 0; i < args.length; i++) 84 { 85 code = (31 * code) + args[i].hashCode(); 86 } 87 } 88 89 return code; 90 } 91 92 93 public boolean equals(Object o) 94 { 95 96 if (this == o) 97 { 98 return true; 99 } 100 101 if (!(o instanceof CallKey)) 102 { 103 return false; 104 } 105 106 final CallKey callKey = (CallKey) o; 107 108 if (!methodName.equals(callKey.methodName)) 109 { 110 return false; 111 } 112 113 if (!Arrays.equals(args, callKey.args)) 114 { 115 return false; 116 } 117 118 return true; 119 } 120 } 121
| Popular Tags
|