Hi,
I need a method that would be used for sorting list of POJOs. In the invocation I pass the list of objects to sort and a field name that would be used in a comparator. I need such method cause it'll be used for some classes that have nothing in common and sorting will be based on different fields. Objects are pulled out from database and I know that the sorting process should be carried on db's side but the lists aren't very long and it can be sorted in Java. Here's my code:
public <T> List<T> sortList(List<T> l, final String s) {
Collections.sort(l, new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
try {
Field f1 = o1.getClass().getDeclaredField(s);
Field f2 = o2.getClass().getDeclaredField(s);
f1.setAccessible(true);
f2.setAccessible(true);
Object v1 = f1.get(o1);
Object v2 = f2.get(o2);
return ((Comparable) v1).compareTo((Comparable) v2);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
};
});
return l;
}
And the question is to how to (if it's possible) parametrize the following line:
return ((Comparable) v1).compareTo((Comparable) v2);
that the warning won't be displayed (i know about annotations)?
And maybe there's better idea for implementing such method?