我最近在我最近的 Java 项目的域对象中覆盖了一些 equals
方法。当我们使用 Sonar 计算我们的代码指标时,我立即看到这些类的圈复杂度增加到超过阈值。
我想知道是否有一个聪明的方法、模式或选项来保持这个指标较低,尽管有一点更复杂的 equals
方法。
编辑:这是我的一个例子,我不会说什么具体的,只是为了让我们知道我们在说什么。
@Override
public boolean equals(Object o) {
if (o instanceof MyKey) {
MyKey other = (MyKey) o;
if (this.foo.longValue() == other.getFoo().longValue() &&
this.bar.equalsIgnoreCase(other.getBar()) &&
this.foobar.shortValue() == other.getFoobar().longValue()){
return true;
}
}
return false;
}
@Override
public int hashCode() {
int hash = 3;
hash = 53 * hash + foo.hashCode();
hash = 53 * hash + bar.hashCode();
hash = 53 * hash + foobar.hashCode();
return hash;
}
最佳答案
您可以使用 Apache 的 EqualsBuilder:
public boolean equals(Object obj) {
if (obj == null) { return false; }
if (obj == this) { return true; }
if (obj.getClass() != getClass()) {
return false;
}
MyClass rhs = (MyClass) obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(field1, rhs.field1)
.append(field2, rhs.field2)
.append(field3, rhs.field3)
.isEquals();
}
关于java - 如何在不增加圈复杂度的情况下覆盖等于?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41873772/