java重写集合的contains()方法可以吗?
我在玩Java反射,我想从不同类中声明的方法创建一个方法缓存机制。为了防止随机行为,我想禁止将具有相同签名的方法加载到缓存中(在不同类中声明的方法可以具有相同的签名)
我找到的唯一方法是重写我缓存方法的集合的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);
}
}
}
谢谢
# 1 楼答案
重写“contains()”方法是完全可以的,但是,它通常是不必要的。contains()方法的目的只是检查集合中是否已经存在等效对象
将使用特定对象集合的“equals”方法来确定这一点
但是,如果您想要为无法嵌入到对象中的contains定制行为,可能需要破解contains()方法。我认为,考虑到您试图缓存java方法的事实,您可能希望将“contains”逻辑粘合到包含这些方法的集合中。。。。然而,这并不完全清楚