Assists in implementing {@link java.lang.Comparable#compareTo(Object)} methods.It is consistent with
equals(Object)
and
hashcode()
built with {@link EqualsBuilder} and{@link HashCodeBuilder}.
Two Objects that compare equal using equals(Object)
should normally also compare equal using compareTo(Object)
.
All relevant fields should be included in the calculation of the comparison. Derived fields may be ignored. The same fields, in the same order, should be used in both compareTo(Object)
and equals(Object)
.
To use this class write code as follows:
public class MyClass { String field1; int field2; boolean field3; ... public int compareTo(Object o) { MyClass myClass = (MyClass) o; return new CompareToBuilder() .appendSuper(super.compareTo(o) .append(this.field1, myClass.field1) .append(this.field2, myClass.field2) .append(this.field3, myClass.field3) .toComparison(); } }
Alternatively, there is are {@link #reflectionCompare reflectionCompare} method that usesreflection to determine the fields to append. Because fields can be private, reflectionCompare
uses {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} tobypass normal access control checks. This will fail under a security manager, unless the appropriate permissions are set up correctly. It is also slower than appending explicitly.
A typical implementation of compareTo(Object)
using reflectionCompare
looks like:
public int compareTo(Object o) { return CompareToBuilder.reflectionCompare(this, o); }
@see java.lang.Comparable
@see java.lang.Object#equals(Object)
@see java.lang.Object#hashCode()
@see EqualsBuilder
@see HashCodeBuilder
@author
Steve Downey
@author Stephen Colebourne
@author Gary Gregory
@author Pete Gieser
@since 1.0
@version $Id: CompareToBuilder.java 161243 2005-04-14 04:30:28Z ggregory $