重载 equals¶
ID: java/wrong-equals-signature
Kind: problem
Security severity:
Severity: error
Precision: medium
Tags:
- reliability
- correctness
Query suites:
- java-security-and-quality.qls
定义参数类型不是 Object
的 equals
方法的类会重载 Object.equals
方法,而不是覆盖它。这可能不是本意。
建议¶
要覆盖 Object.equals
方法,equals
方法的参数必须具有 Object
类型。
示例¶
在以下示例中,类 BadPoint
的定义不会覆盖 Object.equals
方法。这意味着 p.equals(q)
解析为 Object.equals
的默认定义并返回 false
。类 GoodPoint
正确覆盖了 Object.equals
,因此 r.equals(s)
返回 true
。
class BadPoint {
int x;
int y;
BadPoint(int x, int y) {
this.x = x;
this.y = y;
}
// overloaded equals method -- should be avoided
public boolean equals(BadPoint q) {
return x == q.x && y == q.y;
}
}
BadPoint p = new BadPoint(1, 2);
Object q = new BadPoint(1, 2);
boolean badEquals = p.equals(q); // evaluates to false
class GoodPoint {
int x;
int y;
GoodPoint(int x, int y) {
this.x = x;
this.y = y;
}
// correctly overrides Object.equals(Object)
public boolean equals(Object obj) {
if (obj != null && getClass() == obj.getClass()) {
GoodPoint q = (GoodPoint)obj;
return x == q.x && y == q.y;
}
return false;
}
}
GoodPoint r = new GoodPoint(1, 2);
Object s = new GoodPoint(1, 2);
boolean goodEquals = r.equals(s); // evaluates to true
参考¶
J. Bloch,Effective Java(第二版),第 8 项。Addison-Wesley,2008 年。
Java 语言规范:覆盖(通过实例方法),重载。
Java 教程:覆盖和隐藏方法。