package com.gov.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/***
* 用户排序
* @author huangwei
* 2015年7月1日
* @param <E>
*/
public class SortList<E> {
public void Sort(List<E> list, final String method, final String sort) {
Collections.sort(list, new Comparator() {
public int compare(Object a, Object b) {
int ret = 0;
try {
Method m1 = ((E) a).getClass().getMethod(method, null);
Method m2 = ((E) b).getClass().getMethod(method, null);
if (sort != null && "desc".equals(sort))// 倒序
ret = m2.invoke(((E) b), null).toString()
.compareTo(m1.invoke(((E) a), null).toString());
else
// 正序
ret = m1.invoke(((E) a), null).toString()
.compareTo(m2.invoke(((E) b), null).toString());
} catch (NoSuchMethodException ne) {
System.out.println(ne);
} catch (IllegalAccessException ie) {
System.out.println(ie);
} catch (InvocationTargetException it) {
System.out.println(it);
}
return ret;
}
});
}
}
调用:
List<OrderInfoBean> orderInfoBeans = commitOrderDto.getValue();
SortList<OrderInfoBean> sortList = new SortList<OrderInfoBean>();
sortList.Sort(orderInfoBeans, "getCreateTime", "desc");
参数介绍:
第一个参数:是需要排序的list
第二个参数:排序字段的get方法,例如,我我需要根据id排序,就传getId
第三个参数:升序。降序