// CS 1621 Fall 2005 // Somewhat generic comparator in Java. Most of this code was taken from // an example provided by Gervase Gallant // [see http://www.javazoid.com/foj_arrays.html]. I modified it a bit // to use methods rather than fields for the comparisons. import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class GenericComparator implements Comparator { public static final String ASC="asc"; public static final String DESC="desc"; private String compareMethod = null; private String sortOrder = null; public GenericComparator(String method, String order) { super(); this.compareMethod = method; if (order == null || order.equals(ASC)){ this.sortOrder=ASC; } else if (order.equals(DESC)){ this.sortOrder=DESC; } } public GenericComparator(String method){ this(method,"asc"); } public int compare(Object o1, Object o2) { Object value1; Object value2; try{ Method m = this.getMethod(o1); if (m == null) return 0; if (this.sortOrder.equals(ASC)) { value1 = m.invoke(o1); value2 = m.invoke(o2); } else { value2 = m.invoke(o1); value1 = m.invoke(o2); } return this.compareField( value1, value2); }catch (Exception nsfe){ System.out.println(nsfe); return 0; } } private int compareField(Object value1, Object value2) throws IllegalAccessException{ if (value1 instanceof Comparable){ return ((Comparable) value1).compareTo(value2); } else { return value1.toString().compareTo(value2.toString()); //try String sort. } } private Method getMethod(Object object){ Method [] methods = object.getClass().getMethods(); for (int i = 0; i < methods.length; i++){ if (methods[i].getName().equals(this.compareMethod)){ return methods[i]; } } System.out.println("Sorry...couldn't sort on " + this.compareMethod); return null; } }