Lazy Class Infrastructure

Do you ever feel you should implement equals(),
hashCode() and toString, but just can’t be bothered to
do it for every class? Well, if you aren’t bothered by speed, you can
use Jakarta Commons Lang to do it for you. Just add this to your class:

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

class Foo {
   public int hashCode() {
      return HashCodeBuilder.reflectionHashCode(this);
   public boolean equals(Object other) {
      return EqualsBuilder.reflectionEquals(this,other);
   public String toString() {
      return ToStringBuilder.reflectionToString(this);

And that’s it. Your class will just do the right thing. As you can
probably guess from the function names, it uses reflection, so may be
suboptimal. If you need performance, you can use tell it to use
particular members, but I think I’ll leave that up to a future article.
I also recommend you don’t use this technique if you are using something
like Hibernate, which does
things behind the scenes on member access; you may find it does
undesirable things. 🙂

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.