/**
* 对集合中元素按照指定方法进行排序
*
* @param list 需要排序的集合
* @param property 时间对象在集合对象中属性名称
* @param method 排序字段get方法
* @param reverse 是否倒序
*/
public static
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;
}
});
}