List通用排序

//通用排序
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;
}
});
}
}



調用:

SortList<TbNews> sortList = new SortList<TbNews>();
// 排序 list爲集合,getNdate根據哪個字段排序,desc排序方式
sortList.Sort(list, "getNdate", "desc");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章