Atom Feed SITE FEED   ADD TO GOOGLE READER

JavaBeans in Comparators

Data objects are the new orange! So I am continuously coding data objects and I find myself writing a lot of repetitive comparison code:
public int compareTo(Object other) {
if(other == null) return -1;
Car otherCar = (Car)other;

if(myColor == null && otherCar.getColor() != null) return -1;
if(myColor.compareTo(otherCar.getColor() != 0) return myColor.compareTo(otherCar.getColor());

if(mySpeed == null && otherCar.getSpeed() != null) return -1;
if(mySpeed.compareTo(otherCar. getSpeed() != 0) return mySpeed.compareTo(otherCar. getSpeed());

if(myYear == null && otherCar.getYear() != null) return -1;
if(myYear.compareTo(otherCar. getYear() != 0) return myYear.compareTo(otherCar. getYear());

return 0;
}


So now I have a new class called Comparators. It has a handy method that gets a custom comparator, given a handful of properties to test in sequence:
private static String[] compareProperties = new String[] { "color", "speed", "year" };
private static Comparator comparator = Comparator.properties(Car.class, compareProperties };
public int compareTo(Object other) {
return comparator.compare(this, other);
}


Reflection and JavaBeans are great! Now all I need to do is extend this so that it also works with equals() and hashCode().