1.7. Automating compareTo( )
Problem
You need a quick way to implement compareTo( )
methods.
Solution
Commons Lang CompareToBuilder provides a builder
for compareTo( ) methods.
CompareToBuilder
can perform a comparison via reflection, or a comparison can be
customized by passing parameters to an instance of
CompareToBuilder. The following example
demonstrates the use of the reflection builder to implement a
compareTo( ) method. This implementation compares
all nonstatic and nontransient member variables in both classes.
import org.apache.commons.lang.builder.CompareToBuilder;
// Build a compareTo function from reflection
public int compareTo(Object o) {
return CompareToBuilder.reflectionCompare(this, obj);
}Discussion
CompareToBuilder.reflectionCompare( ) takes two
objects and compares the non-static, nontransient member variables of
these objects. In Example 1-2, the comparison
involves the name properties of two
PoliticalCandidate objects from Example 1-3, which are considered equal if both
firstName and lastName are
equal. reflectionCompare( ) ignores static fields
and transients; therefore, in Example 1-3,
averageAge and fullName do not
contribute to the automated comparison.
Example 1-3. Implementing compareTo( ) using a reflection builder
public class PoliticalCandidate { // Static variable private static String averageAge; // Member variables private String firstName; private String lastName; private transient String fullName; // Constructors // get/set methods // Build a ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access