Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.springframework.data.domain.Sort;
- import org.springframework.util.StringUtils;
- import java.lang.reflect.Method;
- import java.util.Comparator;
- import static org.springframework.data.domain.Sort.Direction.ASC;
- public class DynamicComparatorFactory {
- public static <T> Comparator getComparator(Class<T> cl, Sort.Order... orders) {
- return (Comparator<T>) (c1, c2) -> {
- for (Sort.Order order : orders) {
- try {
- Method method = c1.getClass().getMethod("get" + StringUtils.capitalize(order.getProperty()));
- Comparable s1 = (Comparable) method.invoke(c1);
- Comparable s2 = (Comparable) method.invoke(c2);
- int result = ((order.getDirection() == ASC) ? 1 : -1) * s1.compareTo(s2);
- if (result != 0) {
- return result;
- }
- } catch (Exception e) {
- }
- }
- return 0;
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement