我在玩Java反射,并且想从不同类中声明的方法创建方法缓存机制。为了防止随机行为,我想禁止加载具有相同签名的方法到Cache(在不同类中声明的方法可以具有相同的签名)。重写Set的contains()方法可以吗?
我发现这样做的唯一方法是重写集缓存方法的Set的contains()方法。
这样做有危险吗?你有什么更好的主意来实现这一目标?
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);
}
}
}
谢谢!
您真的只想缓存方法的一个版本,无论它声明的类是什么?这似乎是一个奇怪的要求... – ig0774
@ ig0774:我没有任何要求,我只是在玩耍。但对我来说这似乎并不奇怪,如果你有一个web servlet应该在你的web服务器上执行一个方法呢?您可能希望能够在不同类中声明可执行方法以提高代码的可读性,并且您当然不希望客户不必担心您声明方法的位置...... – nbarraille