java反射练习 对集合中元素 按照方法进行排序

/** * 对集合中元素按照指定方法进行排序 * * @param list 需要排序的集合 * @param property 时间对象在集合对象中属性名称 * @param method 排序字段get方法 * @param reverse 是否倒序 */ public static void sortByMethod(List list, final String property, final String method, final boolean reverse) { Collections.sort(list, new Comparator() { public int compare(Object arg1, Object arg2) { int result = 0; if (arg1 == null || arg2 == null) { return 0; }

        try {
            Field property1 = (arg1).getClass().getDeclaredField(property);
            if(!property1.isAccessible()){
                property1.setAccessible(true);
            }

            // 获取时间对象
            Object object1 = property1.get(arg1);

            Field property2 = (arg2).getClass().getDeclaredField(property);
            if(!property2.isAccessible()){
                property2.setAccessible(true);
            }
            // 获取时间对象
            Object object2 = property2.get(arg2);

            Method m1 = object1.getClass().getMethod(method, null);
            Method m2 = object2.getClass().getMethod(method, null);

            Object obj1 = m1.invoke(object1, null);
            Object obj2 = m2.invoke(object2, null);

            if (obj1 instanceof String) {
                // 字符串
                result = obj1.toString().compareTo(obj2.toString());
            } else if (obj1 instanceof Date) {
                // 日期类型
                if (obj1 == null || obj2 == null) {
                    return 0;
                }

                long time = ((Date) obj1).getTime() - ((Date) obj2).getTime();
                if (time > 0) {
                    result = 1;
                } else if (time < 0) {
                    result = -1;
                } else {
                    result = 0;
                }
            } else if (obj1 instanceof Short) {
                result = (Short) obj1 - (Short) obj2;
            }

            if (reverse) {
                // 倒序
                result = -result;
            }

        } catch (NoSuchMethodException e) {
            logger.error("获取对象方法出错,对象中没有当前方法 == >> " + e.toString(), e);
        } catch (IllegalAccessException iae) {
            logger.error("获取对象属性权限出错 == >> " + iae.toString(), iae);
        } catch (InvocationTargetException ite) {
            logger.error("此处接收被调用方法内部未被捕获的异常 == >> " + ite.toString(), ite);
        } catch (NoSuchFieldException e) {
            logger.error("获取对象属性出错,对象中没有当前属性 == >> " + e.toString(), e);
        }

        return result;
    }
});

}

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0