package org.nhooo.example.commons.lang;
public class ObjectEqualsDemo {
public static void main(String[] args) {
Book book1 = new Book(1L, "Spring Boot in Action", "Craig Walls");
Book book2 = new Book(2L, "Docker in Action", "Jeff Nickoloff");
Book book3 = book1;
System.out.println("book1.equals(book2) = " + book1.equals(book2));
System.out.println("book3.equals(book1) = " + book3.equals(book1));
}
}package org.nhooo.example.commons.lang;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.io.Serializable;
public class Book implements Serializable {
private Long id;
private String title;
private String author;
public Book(Long id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
}
//〜在这里实现获取器和设置器。
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Book)) {
return false;
}
Book that = (Book) o;
return new EqualsBuilder()
.append(this.id, that.id)
.append(this.title, that.title)
.append(this.author, that.author)
.isEquals();
// 您还可以使用EqualsBuilder类的反射。
// 返回EqualsBuilder.reflectionEquals(this,that);
}
public int hashCode() {
return new HashCodeBuilder()
.append(id)
.append(title)
.append(author)
.toHashCode();
// 甚至使用最简单的反射方法
// 下面。
// 返回HashCodeBuilder.reflectionHashCode(this);
}
}
Maven依赖
org.apache.commons
commons-lang3
3.9