Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

Creating a toString method used to be tedious and would lead to new properties being left out. Jakarta Commons solved that problem for us:

    /**
     * Returns a string representation of the object. In general, the <code>toString</code> method returns a string that
     * "textually represents" this object. 
     * @return a string representation of the object.
     */
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

They also provide a HashCodeBuilder class to make creating a hash code easy

HashCodeBuilder hashCodeBuilder = new HashCodeBuilder();
hashCodeBuilder.append(myProperty).append(myOtherProperty).toHashCode();

Append as many properties as needed, then generate the value.

If you want to use all of the properties of the object to generate the hash code, then:

return HashCodeBuilder.reflectionHashCode(this);

The same functionality has been provided for equals() methods via the EqualsBuilder:

EqualsBuilder equalsBuilder = new EqualsBuilder();
equalsBuilder.appendSuper(super.equals(them));  // don't ignore the parent
equalsBuilder.append(myKey, them.getMyKey()).append(myOtherKey, them.getMyOtherKey()).isEquals();

If you want to use all of the properties of the object to generate the equals method, then:

EqualsBuilder.reflectionEquals(this, them);

January 11th, 2011

Posted In: Java

3 Comments

  • Ted Young says:

    Great summary. Unfortunately, testing these types of methods remains tedious (if you are looking for 100% coverage). I am just finishing up a set of posts on how to extend JUnit to automate the testing of toString, equals, and hashCode. They seem like a nice followup to your post here.

  • I don’t get hung up on testing every method. These methods will not have any business logic or data operations. They are just for researching problems in production. As long as they spit out the fields, they can help me solve the problem at hand. The equals/hashcode methods are a little different and could be involved in the business processes. These are easily tested with a few lines of code, if necessary.

    Nice blog btw. I added you to my rss feeds.

  • Ted Young says:

    I agree with you completely. Unfortunately, I aim for complete code coverage. This is a hot debate of course. Personally, I pursue the code coverage so I can keep track of what I have and haven’t tested yet.

    Thank you, and I have subscribed to yours as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

WP to LinkedIn Auto Publish Powered By : XYZScripts.com