A Value Object Base Class

Value Objects (aka Data Objects) are pretty common. They typically have little or no functionality, but rather just contain one or more data fields. They’re used to represent database entities, to represent model objects in MVC applications, etc.

To be well-behaved members of Collections they should have good hashCode() and equals() methods, and for debugging should have good toString() methods. To be stored in a Session, they must be serializable. So I’ve developed a simple abstract base class that meets these requirements.

It uses Jakarta Commons Lang utility classes for default reflection-based implementations of hashCode(), equals(), and toString(), it implements Serializable, and has a Logger1 in case concrete subclasses need it. The logger is transient because it isn’t serializable, and also shouldn’t be included in hashCode(), equals(), and toString() (Commons Lang ignores transients by default).

Of course any concrete subclass can override any of the three methods if the default implementation isn’t sufficient. But I find that’s the exception rather than the norm.

The code:

package com.foo.bar.model;

import java.io.Serializable;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;

 * Abstract base class for value objects. Contains reflection-based default
 * methods for hashCode, equals, and toString.
 * @author Burt
public abstract class DataObject implements Serializable {

  protected transient final Logger _log = Logger.getLogger(getClass());

  public String toString() {
    return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);

  public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);

  public boolean equals(final Object other) {
    return EqualsBuilder.reflectionEquals(this, other);
  1. I gave up on Commons Logging a while ago since I always use Log4j[back]

Comments are closed.

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 License.