I have a List
of Value Objects [VO]. These Objects have many properties and corresponding get/set methods. I want to sort this List
based on a property which I'll be getting in runtime.
Let me explain in detail...
My VO is like this:
public class Employee {
String name;
String id;
private String getName() {
return name;
}
private String getId() {
return id;
}
}
I will be getting a string sortType
in runtime, which can be either "id"
or "name"
. I want to sort the list based on the value of the String
.
I have tried to use Comparator
and reflection together, but no luck. May be I didn't use it properly. I don’t want to use conditional if
block branching to create whichever new specific Comparator
[anonymous inner Class] is needed (at the runtime). Any other thoughts?
The try catch should be inside the new class. Here is the working code. If you want to use a separate class for Comparator
, please find it in @Bohemian's comment below.
String sortType = "name"; // determined at runtime
Collections.sort(results, new Comparator<Employee>() {
public int compare(Employee c1, Employee c2) {
try{
Method m = c1.getClass().getMethod("get" + StringUtils.capitalize(sortType));
String s1 = (String)m.invoke(c1);
String s2 = (String)m.invoke(c2);
return s1.compareTo(s2);
}
catch (Exception e) {
return 0;
}
}
});