Advertisement
Anzak

Untitled

Jan 21st, 2020
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.02 KB | None | 0 0
  1. import org.springframework.data.domain.Sort;
  2. import org.springframework.util.StringUtils;
  3.  
  4. import java.lang.reflect.Method;
  5. import java.util.Comparator;
  6.  
  7. import static org.springframework.data.domain.Sort.Direction.ASC;
  8.  
  9. public class DynamicComparatorFactory {
  10.  
  11.     public static <T> Comparator getComparator(Class<T> cl, Sort.Order... orders) {
  12.         return (Comparator<T>) (c1, c2) -> {
  13.             for (Sort.Order order : orders) {
  14.                 try {
  15.                     Method method = c1.getClass().getMethod("get" + StringUtils.capitalize(order.getProperty()));
  16.                     Comparable s1 = (Comparable) method.invoke(c1);
  17.                     Comparable s2 = (Comparable) method.invoke(c2);
  18.                     int result =  ((order.getDirection() == ASC) ? 1 : -1) * s1.compareTo(s2);
  19.                     if (result != 0) {
  20.                         return result;
  21.                     }
  22.                 } catch (Exception e) {
  23.                 }
  24.             }
  25.             return 0;
  26.         };
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement