如果您有幸使用JDK 7 ,那么新的可用Objects類 ( 至少對我來說 )是實現“通用” Java對象方法(例如equals(Object) [with Objects.equals(Object,Object ) ], hashCode() [帶有Objects.hashCode(Object)或Objects.hash(Object…) ]和toString() [帶有Objects.toString(Object) ]以適當地覆蓋默認的Object實現。 我寫過有關使用Objects類的文章: JDK 7:New Objects類和Java 7 Objects-Powered Compact Equals 。
如果你還沒有使用Java 7,你最好的選擇可能是Apache的百科全書建設者ToStringBuilder和EqualsBuilder和HashCodeBuilder (如果你之前使用的Java版本,以J2SE 5)或番石榴 (如果你使用J2SE 5或后來)。 在本文中,我將研究如何使用Guava的Objects類來實現三種常見的方法equals
, hashCode
和toString()
。
在沒有Guava或其他庫的幫助下,本文中討論的三種常見方法通常會突出顯示,如下面的代碼清單所示。 這些方法是使用NetBeans 7.1 beta生成的。
傳統員工
package dustin.examples;import java.util.Calendar;/*** Simple employee class using NetBeans-generated 'common' methods* implementations that are typical of many such implementations created* without Guava or other library.* * @author Dustin*/
public class TraditionalEmployee
{public enum Gender{ FEMALE, MALE };private final String lastName;private final String firstName;private final String employerName;private final Gender gender;/*** Create an instance of me.* * @param newLastName The new last name my instance will have.* @param newFirstName The new first name my instance will have.* @param newEmployerName The employer name my instance will have.* @param newGender The gender of my instance.*/public TraditionalEmployee(final String newLastName, final String newFirstName,final String newEmployerName, final Gender newGender){this.lastName = newLastName;this.firstName = newFirstName;this.employerName = newEmployerName;this.gender = newGender;}public String getEmployerName(){return this.employerName;}public String getFirstName(){return this.firstName;}public Gender getGender(){return this.gender;}public String getLastName(){return this.lastName;}/*** NetBeans-generated method that compares provided object to me for equality.* * @param obj Object to be compared to me for equality.* @return {@code true} if provided object is considered equal to me or* {@code false} if provided object is not considered equal to me.*/@Overridepublic boolean equals(Object obj){if (obj == null){return false;}if (getClass() != obj.getClass()){return false;}final TraditionalEmployee other = (TraditionalEmployee) obj;if ((this.lastName == null) ? (other.lastName != null) : !this.lastName.equals(other.lastName)){return false;}if ((this.firstName == null) ? (other.firstName != null) : !this.firstName.equals(other.firstName)){return false;}if ((this.employerName == null) ? (other.employerName != null) : !this.employerName.equals(other.employerName)){return false;}if (this.gender != other.gender){return false;}return true;}/*** NetBeans-generated method that provides hash code of this employee instance.* * @return My hash code.*/@Overridepublic int hashCode(){int hash = 3;hash = 19 * hash + (this.lastName != null ? this.lastName.hashCode() : 0);hash = 19 * hash + (this.firstName != null ? this.firstName.hashCode() : 0);hash = 19 * hash + (this.employerName != null ? this.employerName.hashCode() : 0);hash = 19 * hash + (this.gender != null ? this.gender.hashCode() : 0);return hash;}/*** NetBeans-generated method that provides String representation of employee* instance.* * @return My String representation.*/@Overridepublic String toString(){return 'TraditionalEmployee{' + 'lastName=' + lastName + ', firstName=' + firstName+ ', employerName=' + employerName + ', gender=' + gender + '}';}
}
盡管NetBeans 7.1 Beta在這里完成了繁重的工作,但仍必須維護此代碼,并使它們更具可讀性。 下一個類是相同的類,但是具有Guava支持的通用方法,而不是上面顯示的NetBeans生成的“典型”實現。
番石榴員工
package dustin.examples;/*** Simple employee class using Guava-powered 'common' methods implementations.* * I explicitly scope the com.google.common.base.Objects class here to avoid the* inherent name collision with the java.util.Objects class.* * @author Dustin*/
public class GuavaEmployee
{public enum Gender{ FEMALE, MALE };private final String lastName;private final String firstName;private final String employerName;private final TraditionalEmployee.Gender gender;/*** Create an instance of me.* * @param newLastName The new last name my instance will have.* @param newFirstName The new first name my instance will have.* @param newEmployerName The employer name my instance will have.* @param newGender The gender of my instance.*/public GuavaEmployee(final String newLastName, final String newFirstName,final String newEmployerName, final TraditionalEmployee.Gender newGender){this.lastName = newLastName;this.firstName = newFirstName;this.employerName = newEmployerName;this.gender = newGender;}public String getEmployerName(){return this.employerName;}public String getFirstName(){return this.firstName;}public TraditionalEmployee.Gender getGender(){return this.gender;}public String getLastName(){return this.lastName;}/*** Using Guava to compare provided object to me for equality.* * @param obj Object to be compared to me for equality.* @return {@code true} if provided object is considered equal to me or* {@code false} if provided object is not considered equal to me.*/@Overridepublic boolean equals(Object obj){if (obj == null){return false;}if (getClass() != obj.getClass()){return false;}final GuavaEmployee other = (GuavaEmployee) obj;return com.google.common.base.Objects.equal(this.lastName, other.lastName)&& com.google.common.base.Objects.equal(this.firstName, other.firstName)&& com.google.common.base.Objects.equal(this.employerName, other.employerName)&& com.google.common.base.Objects.equal(this.gender, other.gender);}/*** Uses Guava to assist in providing hash code of this employee instance.* * @return My hash code.*/@Overridepublic int hashCode(){return com.google.common.base.Objects.hashCode(this.lastName, this.firstName, this.employerName, this.gender);}/*** Method using Guava to provide String representation of this employee* instance.* * @return My String representation.*/@Overridepublic String toString(){return com.google.common.base.Objects.toStringHelper(this).addValue(this.lastName).addValue(this.firstName).addValue(this.employerName).addValue(this.gender).toString();}
}
如上面的代碼所示,Guava的使用提高了三種常用方法的實現的可讀性。 唯一不好的是需要在代碼中顯式定義Guava的Objects
類,以避免與Java SE 7的Objects類發生命名沖突。 當然,如果不是使用Java 7,那么這不是問題,如果使用Java 7,則無論如何都應該使用標準版本。
結論
Guava通過其Objects
類提供了一種構建更安全,更易讀的通用方法的好方法。 盡管我將對JDK 7項目使用新的java.util.Objects
類,但是Guava的com.google.common.base.Objects
類為在JDK 7之前的Java版本中工作提供了一個不錯的選擇。
參考: Guava的Objects類:來自JCG合作伙伴 Dustin Marx的Equals,HashCode和ToString,來自Inspired by Actual Events博客。
翻譯自: https://www.javacodegeeks.com/2012/11/guavas-objects-class-equals-hashcode-and-tostring.html