Anzak icon

Untitled

Anzak | PRO | 01/21/20 08:15:14 AM UTC | 0 ⭐ | 225 👁️ | Never ⏰ | []
Java |

1.02 KB

|

None

|

0 👍

/

0 👎

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;
        };
    }
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎