import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Date;import java.util.List;/** * 排序List * @param排序的对象 */public class SortList { public void sort(java.util.List 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; } }); } public static void main(String[] args)throws Exception{ class UserInfo{ private Integer id; private String name; private Date date; public UserInfo(Integer id, String name, Date date){ this.id = id; this.name = name; this.date = date; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDate() { return date; } public String getDateFormatted() { return new SimpleDateFormat("yyyy-MM-dd").format(date); } public void setDate(Date date) { this.date = date; } @Override public String toString() { return id + ", " + name + ", " + getDateFormatted(); } } List list = new ArrayList (); SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); list.add(new UserInfo(3,"b",formater.parse("1980-12-01"))); list.add(new UserInfo(1,"c",formater.parse("1980-10-01"))); list.add(new UserInfo(2,"a",formater.parse("1973-10-01"))); System.out.println("-------原来序列-------------------"); for(UserInfo user : list){ System.out.println(user.toString()); } //调用排序类 SortList sortList = new SortList (); System.out.println("--------按id排序------------------"); sortList.sort(list, "getId", "desc"); for(UserInfo user : list){ System.out.println(user.toString()); } System.out.println("---------按name排序-----------------"); sortList.sort(list, "getName", null); for(UserInfo user : list){ System.out.println(user.toString()); } System.out.println("---------按date排序-----------------"); sortList.sort(list, "getDateFormatted", null); for(UserInfo user : list){ System.out.println(user.toString()); } }}