Template toString(), hasCode() and equals() in Eclipse

I am using the following template in Eclipse to output a standard pattern for toString(), hashCode() and equals(). By default I use Apache commons lang.

   @Override
   public String toString() {
      return new org.apache.commons.lang.builder.ToStringBuilder${cursor}(this).append("some field", someField)
            .append("some field", someField).toString();
   }

   @Override
   public int hashCode() {
      return new org.apache.commons.lang.builder.HashCodeBuilder()
            .append(someField).append(someField).toHashCode();
   }

   @Override
   public boolean equals(final Object obj) {
      if (obj == this) {
         return true;  // test for reference equality
      }
      if (obj == null) {
         return false; // test for null
      }
      if (obj instanceof ${enclosing_type}) {
         final ${enclosing_type} other =
               (${enclosing_type}) obj;
         return org.apache.commons.lang.ObjectUtils.equals(someField, other.someField)
               && ObjectUtils.equals(someField, other.someField);
      } else {
         return false;
      }
   }

In Eclipse, I enter this through Window > Preferences > Java > Editor > Templates > click New, and enter details as below.

Template I use in Eclipse for toString(), hashCode() and equals() - click to expand

Note that I include the fully qualified name of the utility classes (such as org.apache.commons.lang.builder.HashCodeBuilder) just once so that I can easily import them through Eclipse by clicking on the fully qualified name and pressing control+shift+m.

As mentioned above, I am using Apache commons lang by default. However as explained by Sean Patrick Floyd in this StackOverflow post, guava-libraries are also a good choice. Java 7's Objects class has an equals(Object a, Object b) utility method that will serve for part of this too.

Although toString(), hashCode() and equals() may seem simple enough, there are many pitfalls to be aware of when implementing these methods. I recommend reading Effective Java (2nd Edition) by Joshua Bloch to learn more (available as an Amazon Kindle eBook).

Popular Posts