自定义的字段实现排序

时间:2022-07-17 19:54:57

通过反射实现

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static javax.management.openmbean.SimpleType.DATE;
import static javax.management.openmbean.SimpleType.STRING;

/**
 * @author yan.kang
 * @version 1.0
 * @date 2019-07-11 15:42
 */
public class ResponseSorter {

    private static Pattern linePattern = Pattern.compile("_(\\w)");

    /**
     * 下划线转驼峰
     * @param str
     * @return
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 对象排序器
     * @param targetList
     * @param sortField 给出排序的字段
     * @param sortMode  出给升序 or 降序,默认升序。
     * @param <T>
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public <T> void sort(List<T> targetList, final String sortField, final String sortMode) {
        Collections.sort(targetList, new Comparator() {
            //匿名内部类,重写compare方法
            @Override
            public int compare(Object obj1, Object obj2) {
                Class c = obj1.getClass();
                Integer result = 0;
                try {
                    Field field = c.getDeclaredField(sortField);
                    String classType = field.getType().getTypeName();
                    Method method = c.getMethod("get" + sortField.substring(0, 1).toUpperCase() + sortField.substring(1), new Class[]{});
                    if (STRING.getTypeName().equals(classType)) {
                        result = ((String) method.invoke(obj1)).compareTo((String) method.invoke(obj2));
                    } else if (DATE.getTypeName().equals(classType)) {
                        Long l = ((Date)method.invoke(obj1)).getTime() - ((Date)method.invoke(obj2)).getTime();
                        result = l > 0 ? 1 : l < 0 ? -1 : 0;
                    } else {
                        result = -100;
                        throw new RuntimeException("暂不支持其它类型字段排序,如有需要请自己添加.");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                result = result > 0 ? 1 : result < 0 ? -1 : 0;
                // 默认asc,如果逆序结果取反
                if (Constant.DESC.equalsIgnoreCase(sortMode)) {
                    result = -result;
                }
                return result;
            }
        });
        System.out.println(targetList);
    }
}