I was playing around with Java reflection, and I wanted to create a method caching mechanism from Methods declared in different classes. In order to prevent random behavior, I want to forbid loading methods with the same signature to the Cache (method declared in different classes can have the same signature).
The only way I found of doing this, was to Override the contains() method of the Set where I cache the methods.
Is it dangerous to do so? Do you have any better idea to achieve this?
private final Set<Method> methodsCache;
public MyMethodCachingClass(Set<Class<?>> classes) {
methodsCache = new HashSet<Method>(){
private static final long serialVersionUID = -1467698582662452923L;
/**
* Overwriting the contains method of this Set so that we don't allow multiple methods with the same signature,
* even if they are declared in different classes.
*/
@Override
public boolean contains(Object o) {
if (!(o instanceof Method)) {
return false;
}
Method method = (Method) o;
for (Method m : this) {
if (method.getName().equals(m.getName()) && method.getParameterTypes().equals(m.getParameterTypes())) {
return true;
}
}
return false;
}
};
for (Class<?> c : classes) {
for (Method m : c.getDeclaredMethods()) {
if (methodsCache.contains(m)) {
throw new IllegalArgumentException("The method " + m.getName() + " exists with the same signature in two different classes.");
}
methodsCache.add(m);
}
}
}
Thanks!
Simply use a combination of the following for your cache key:
class name + method name + method parameter types