Below is the method I have. It works fine for comparing Strings. I would like to make it capable of also comparing Dates or possibly any class that has an acceptably defined compareTo method. Looking for an easy way to do this. I was heading down a hacky path. Also open to any other suggestions to improve this method.
protected <E> int compareFields(E o1, E o2,String fieldName){
String o1Data;
String o2Data;
try {
o1Data = (String) o1.getClass().getMethod(fieldName).invoke(o1);
o2Data = (String) o2.getClass().getMethod(fieldName).invoke(o2);
}
catch(Exception e) {
throw new RuntimeException(e);
}
if(o1Data == null && o2Data == null){
return 0;
} else if (o1Data == null){
return 1;
} else if (o2Data == null){
return -1;
}
return o2Data.compareTo(o1Data);
}
Do you mean like the following?
I assume you don’t want to reverse sort your data.