/** * 对集合中元素按照指定方法进行排序 * * @param list 需要排序的集合 * @param property 时间对象在集合对象中属性名称 * @param method 排序字段get方法 * @param reverse 是否倒序 */ public static <T> void sortByMethod(List<T> list, final String property, final String method, final boolean reverse) { Collections.sort(list, new Comparator<T>() { public int compare(Object arg1, Object arg2) { int result = 0; if (arg1 == null || arg2 == null) { return 0; }
1 try { 2 Field property1 = (arg1).getClass().getDeclaredField(property); 3 if(!property1.isAccessible()){ 4 property1.setAccessible(true); 5 } 6 7 // 获取时间对象 8 Object object1 = property1.get(arg1); 9 10 Field property2 = (arg2).getClass().getDeclaredField(property); 11 if(!property2.isAccessible()){ 12 property2.setAccessible(true); 13 } 14 // 获取时间对象 15 Object object2 = property2.get(arg2); 16 17 Method m1 = object1.getClass().getMethod(method, null); 18 Method m2 = object2.getClass().getMethod(method, null); 19 20 Object obj1 = m1.invoke(object1, null); 21 Object obj2 = m2.invoke(object2, null); 22 23 if (obj1 instanceof String) { 24 // 字符串 25 result = obj1.toString().compareTo(obj2.toString()); 26 } else if (obj1 instanceof Date) { 27 // 日期类型 28 if (obj1 == null || obj2 == null) { 29 return 0; 30 } 31 32 long time = ((Date) obj1).getTime() - ((Date) obj2).getTime(); 33 if (time > 0) { 34 result = 1; 35 } else if (time < 0) { 36 result = -1; 37 } else { 38 result = 0; 39 } 40 } else if (obj1 instanceof Short) { 41 result = (Short) obj1 - (Short) obj2; 42 } 43 44 if (reverse) { 45 // 倒序 46 result = -result; 47 } 48 49 } catch (NoSuchMethodException e) { 50 logger.error("获取对象方法出错,对象中没有当前方法 == >> " + e.toString(), e); 51 } catch (IllegalAccessException iae) { 52 logger.error("获取对象属性权限出错 == >> " + iae.toString(), iae); 53 } catch (InvocationTargetException ite) { 54 logger.error("此处接收被调用方法内部未被捕获的异常 == >> " + ite.toString(), ite); 55 } catch (NoSuchFieldException e) { 56 logger.error("获取对象属性出错,对象中没有当前属性 == >> " + e.toString(), e); 57 } 58 59 return result; 60 } 61});
}