@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