`
leon_a
  • 浏览: 79032 次
  • 性别: Icon_minigender_1
  • 来自: 拜月神教
社区版块
存档分类
最新评论

排序小玩意儿

阅读更多
jasperreport没有内置的排序功能;在pdf进行group的时候,除非你在sql中进行了排序,否则group的结果会让人感到很杯具。
所以就写了这个东东。完整代码见附件
几个类:
Order:设置按属性排序,DESC,ASC
Util:设定支持原生类型
Main:排序类

用法:
Order order = new Order().add("city", Order.ASC).add("id", Order.DESC);
List result = m.getOrderedData(list, order);

使用规则:
所有排序的属性都实现了Comparable接口(原生类型会转成包装类型)

另外给出关键代码段
    @SuppressWarnings("unchecked")
    private List<?> getOrderedData(List<?> list, final Order order) {
        Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                try {
                    return compareByOrder(o1, o2, order);
                } catch (Exception e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        };
        Collections.sort(list, comparator);
        return list;
    }

    @SuppressWarnings("unchecked")
    private int compareByOrder(Object obj1, Object obj2, Order order) throws Exception {
        if (order == null) {
            return 0;
        }
        int i = 0;
        while (i < order.size()) {
            String property = order.getKeyByIndex(i);
            Boolean sc = order.getValueByKey(property);
            Comparable p1 = getProperty(obj1, property);
            Comparable p2 = getProperty(obj2, property);
            if (p1 != null && p2 != null) {
                if (p1.compareTo(p2) != 0) {
                    return sc ? p1.compareTo(p2) : p2.compareTo(p1);
                }
            }
            i++;
        }
        return 0;
    }

    @SuppressWarnings("unchecked")
    private Comparable getProperty(Object bean, String property) throws Exception {
        Class<?> clazz = PropertyUtils.getPropertyType(bean, property);
        Object obj = PropertyUtils.getProperty(bean, property);
        if (clazz.isPrimitive()) {
            clazz = Util.getPrimitiveClass2Wrapper(clazz);
            obj = clazz.cast(obj);
        }
        Class<?> tempClazz = clazz;
        boolean flg = false;
        while (tempClazz.getSuperclass() != null) {
            Class[] interfaces = tempClazz.getInterfaces();
            for (int i = 0; i < interfaces.length; i++) {
                if (interfaces[i].getName().equals(Comparable.class.getName())) {
                    flg = true;
                    break;
                }
            }
            tempClazz = tempClazz.getSuperclass();
        }
        if (flg) {
            return (Comparable) obj;
        }
        throw new RuntimeException("the property '" + property + "' must be implement Comparable interface");
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics