@EqualsAndHashCode注解在子类中使用的问题


由于@EqualsAndHashCode生成的Equals和HashCode方法不会包含父类的属性,所以@EqualsAndHashCode(of=“子类属性”)是不合法的。

那么在子类中如果使用父类已有的Equals和HashCode方法,则可以有两种方法:

1. 不使用@EqualsAndHashCode注解,加上下面方法:

@Override
public boolean equals(Object o) {
return super.equals(o);
}

@Override
public int hashCode() {
return super.hashCode();
}

2. 使用@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)

编译后生成的代码如下:

public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof BaseEntity)) {
return false;
} else {
BaseEntity other = (BaseEntity)o;
if (!other.canEqual(this)) {
return false;
} else {
return super.equals(o);
}
}
}

protected boolean canEqual(Object other) {
return other instanceof BaseEntity;
}

public int hashCode() {
int result = super.hashCode();
return result;
}

注意事项:用注解@EqualsAndHashCode(callSuper = true)会报告 StackOverFlow错误,原因是生成的hashcode值超过了int数值的范围造成的,如hashcode()方法如下:

public int hashCode() {
int PRIME = true;
int result = super.hashCode();
Object $category = this.getCategory();
result = result * 59 + ($category == null ? 43 : $category.hashCode());
Object $section = this.getSection();
result = result * 59 + ($section == null ? 43 : $section.hashCode());
Object $compileUnitName = this.getCompileUnitName();
result = result * 59 + ($compileUnitName == null ? 43 : $compileUnitName.hashCode());
Object $confirmationType = this.getConfirmationType();
result = result * 59 + ($confirmationType == null ? 43 : $confirmationType.hashCode());
Object $amount = this.getAmount();
result = result * 59 + ($amount == null ? 43 : $amount.hashCode());
Object $controlAmount = this.getControlAmount();
result = result * 59 + ($controlAmount == null ? 43 : $controlAmount.hashCode());
Object $controlDate = this.getControlDate();
result = result * 59 + ($controlDate == null ? 43 : $controlDate.hashCode());
Object $applyDate = this.getApplyDate();
result = result * 59 + ($applyDate == null ? 43 : $applyDate.hashCode());
Object $replyDate = this.getReplyDate();
result = result * 59 + ($replyDate == null ? 43 : $replyDate.hashCode());
Object $reviewAmount = this.getReviewAmount();
result = result * 59 + ($reviewAmount == null ? 43 : $reviewAmount.hashCode());
Object $projectSection = this.getProjectSection();
result = result * 59 + ($projectSection == null ? 43 : $projectSection.hashCode());
Object $compileUnit = this.getCompileUnit();
result = result * 59 + ($compileUnit == null ? 43 : $compileUnit.hashCode());
return result;
}

 




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM