@EqualsAndHashCode
- 此注解會生成equals(Object other) 和 hashCode()方法炉旷。
- 它默認(rèn)使用非靜態(tài),非瞬態(tài)的屬性
- 可通過參數(shù)exclude排除一些屬性
- 可通過參數(shù)of指定僅使用哪些屬性
- 它默認(rèn)僅使用該類中定義的屬性且不調(diào)用父類的方法
當(dāng)啟動@EqualsAndHashCode時,默認(rèn)不調(diào)用父類的equals方法蜻直,當(dāng)做類型相等判斷時耻陕,會遇到麻煩,例如:
@Data
public class People {
private Integer id;
}
@Data
public class User extends People {
private String name;
private Integer age;
}
public static void main(String[] args) {
User user1 = new User();
user1.setName("jiangxp");
user1.setAge(18);
user1.setId(1);
User user2 = new User();
user2.setName("jiangxp");
user2.setAge(18);
user2.setId(2);
System.out.println(user1.equals(user2));
}
輸出結(jié)果:true
注意:兩條user數(shù)據(jù)绘盟,ID完全不一樣鸠真,結(jié)果明顯是錯的,沒有做id的equals判斷
需要將@EqualsAndHashCode修改為@EqualsAndHashCode(callSuper = true)才能得到正確結(jié)果.
反編譯修改后的User.class龄毡,發(fā)現(xiàn)有些許變化
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof User)) {
return false;
} else {
User other = (User)o;
if (!other.canEqual(this)) {
return false;
} else if (!super.equals(o)) { // (1)此處變化吠卷,調(diào)用了父類的equals,原:無此段邏輯
return false;
} else {
Object this$name = this.getName();
Object other$name = other.getName();
if (this$name == null) {
if (other$name != null) {
return false;
}
} else if (!this$name.equals(other$name)) {
return false;
}
Object this$age = this.getAge();
Object other$age = other.getAge();
if (this$age == null) {
if (other$age != null) {
return false;
}
} else if (!this$age.equals(other$age)) {
return false;
}
return true;
}
}
}
public int hashCode() {
int PRIME = true;
int result = super.hashCode(); //(2)此處變化沦零,調(diào)用了父類的hashCode(); 原:int result = 1;
Object $name = this.getName();
result = result * 59 + ($name == null ? 43 : $name.hashCode());
Object $age = this.getAge();
result = result * 59 + ($age == null ? 43 : $age.hashCode());
return result;
}
總結(jié):(1)和(2)解釋了@EqualsAndHashCode(callSuper = true)的作用.