CodeQL 文档

重载 equals

ID: java/wrong-equals-signature
Kind: problem
Security severity: 
Severity: error
Precision: medium
Tags:
   - reliability
   - correctness
Query suites:
   - java-security-and-quality.qls

单击以在 CodeQL 存储库中查看查询

定义参数类型不是 Objectequals 方法的类会重载 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

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私