zoukankan      html  css  js  c++  java
  • 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;
            }
        });
    }

  • 相关阅读:
    JavaScript 闭包究竟是什么
    Javascript闭包简单理解
    使用border做三角形
    负边距在布局中的使用
    direction和unicode
    CSS 实现打字效果
    你可能没注意的CSS单位
    前端模块化
    JavaScript面向对象
    阿里前端两年随想
  • 原文地址:https://www.cnblogs.com/wangjing666/p/9773701.html
Copyright © 2011-2022 走看看