使用第三方工具覆写Object中方法
我们在实际开发中,经常需要覆写Object中的equals,hashcode,toString方法,其实编写这些代码并不是很难,但很枯燥和乏味。
下面推荐Google的Guava jar包来覆写上面的方法。
直接上代码。
import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.collect.ComparisonChain; public class Book implements Comparable<Book> { private String author; private String title; private String publisher; private String isbn; private double price; public Book(String author, String title, String publisher, String isbn, double price) { this.author = author; this.title = title; this.publisher = publisher; this.isbn = isbn; this.price = price; } public String getAuthor() { return author; } public String getTitle() { return title; } public String getPublisher() { return publisher; } public String getIsbn() { return isbn; } public double getPrice() { return price; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("title", title) .add("author", author) .add("publisher", publisher) .add("price",price) .add("isbn", isbn).toString(); } @Override public int hashCode() { return Objects.hashCode(title, author, publisher, isbn, price); } @Override public boolean equals(Object obj) { return Objects.equal(this, obj); } @Override public int compareTo(Book o) { return ComparisonChain.start() .compare(this.title, o.getTitle()) .compare(this.author, o.getAuthor()) .compare(this.publisher, o.getPublisher()) .compare(this.isbn, o.getIsbn()) .compare(this.price, o.getPrice()) .result(); }
还可以使用apache 的common包里的类来实现。例如下面代码。
package com.lee.bsc.bean; import java.io.Serializable; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import com.lee.util.StringUtil; public class UserBean implements Serializable { /** * */ private static final long serialVersionUID = 3761328140585117680L; private String userId; private boolean login; public UserBean() { } public UserBean(String userId) { this.userId = userId; } public String getUserId() { return userId; } public boolean isLogin() { return login; } public void setUserId(String userId) { this.userId = userId; } public void setLogin(boolean login) { this.login = login; } @Override public int hashCode() { return new HashCodeBuilder().append(userId).toHashCode(); } @Override public boolean equals(Object other) { if (!(other instanceof UserBean)) { return false; } UserBean castOther = new UserBean(); return new EqualsBuilder().append(this.getUserId(), castOther.getUserId()).isEquals(); } @Override public String toString() { return new ToStringBuilder(this, StringUtil.getToStringStyle()) .append("userId", userId) .append("login", login).toString(); } }