Lombok中使用@EqualsAndHashCode注解
- 此注解会生成
equals(Object other)
和hashCode()
方法。 - 它默认使用非静态,非瞬态的属性
- 可通过参数 exclude 排除一些属性
- 可通过参数 of 指定仅使用哪些属性
- 它默认仅使用该类中定义的属性且不调用父类的方法,可以通过
classSuper = true
解决,让其生成的方法中调用父类的方法。
当有多个类有相同的部分属性,把它们定义到父类,恰好id也在父类中,那么当这些对象进行比较时,因为Lombok生成的 equals(Object other)
和 hashCode()
方法而判定为相等。
@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));
}
输出结果:true
但实际上,两条数据是不相等的,因为Id完全不一样的。
如果将 @EqualsAndHashCode
改成 @EqualsAndHashCode(callSuper = true)
就可以得到正确的结果。反编译修改后的class
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)) { // 注意
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(); //注意
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;
}
参考引用: