Easy toString/equals/hashcode javacode 9085791

Easy toString/equals/hashcode

A simple, standard and reusable way of creating toString, equals and hashcode methods in your classes/beans can be found in the jakarta commons.lang package:

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;
public class BaseBean {
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
    }
    public boolean equals(Object o) {
        return EqualsBuilder.reflectionEquals(this, o);
    }

    public int hashCode() {
//             EDIT: this hashCode-implementation seems to break Hibernate:
//             it throws a LazyInitializationException
//    return HashCodeBuilder.reflectionHashCode(this);
//
//             using this implementation for now
        return new HashCodeBuilder(25, 71) // random odd numbers
                .append(this.getId())  // a field in BaseBean, not shown for brevity
                .append(super.hashCode()) // using the standard hashcode too
                .toHashCode();
    }
}

5 Comments

  1. Pingback: Free Credit Report April 25, 2007
  2. Cyrill October 12, 2004
  3. Leon van Tegelen August 30, 2004
  4. Leon van Tegelen August 30, 2004
  5. AH August 30, 2004
  6. Zeger Hendrikse August 30, 2004