java實現按對象某個字段排序,排序字段和規則自定義


@SuppressWarnings({ "unchecked", "rawtypes" })
private <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().getSimpleName();
                    Method method = null;
                    if (BIGDECIMAL.equals(classType)) {
                        method = c.getMethod("get" + sortField.substring(0, 1).toUpperCase() + sortField.substring(1), new Class[]{});
                        if (BizConstants.DESC.equalsIgnoreCase(sortMode)) {
                            result = ((BigDecimal) method.invoke(obj2)).compareTo((BigDecimal) method.invoke(obj1));
                        } else if (BizConstants.DESC.equalsIgnoreCase(sortMode)) {
                            result = ((BigDecimal) method.invoke(obj1)).compareTo((BigDecimal) method.invoke(obj2));
                        }
                    } else {
                        result = -100;
                        throw new RuntimeException("暫不支持其它類型字段排序,如有需要請自己添加.");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            return result > 0 ? 1 : result < 0 ? -1 : 0;
        }
    });
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM