I have a REST endpoint and I want the UI to pass the field name that they want to sort their result by. 'id', 'name', etc. I came up with below, but was really trying to use Reflection / Generics so this could be expanded to encompass every object in my project.
I feel like this solution isn't easily maintainable if I want to have the same functionality for 100 different classes.
public static void sort(List<MovieDTO> collection, String field){
if(collection == null || collection.size() < 1 || field == null || field.isEmpty()){
return;
}
switch(field.trim().toLowerCase()){
case "id":
collection.sort(Comparator.comparing(MovieDTO::getId));
break;
case "name":
collection.sort(Comparator.comparing(MovieDTO::getName));
break;
case "year":
collection.sort(Comparator.comparing(MovieDTO::getYear));
break;
case "rating":
collection.sort(Comparator.comparing(MovieDTO::getRating));
break;
default:
collection.sort(Comparator.comparing(MovieDTO::getId));
break;
}
}
Any ideas on how I could implement this better so that it can be expanded to work for an enterprise application with little maintenance?
Aucun commentaire:
Enregistrer un commentaire