List对象排序通用方法

 1 import java.util.Collections;
 2 import java.util.Comparator;
 3 import java.util.List;
 4 import java.lang.reflect.Method;
 5 import java.lang.reflect.InvocationTargetException;
 6 /**
 7 * 通用排序
 8 */
 9 public class SortList<E>{    
10     public void Sort(List<E> list, final String method, final String sort){
11         Collections.sort(list, new Comparator() {            
12             public int compare(Object a, Object b) {
13                 int ret = 0;
14                 try{
15                     Method m1 = ((E)a).getClass().getMethod(method, null);
16                     Method m2 = ((E)b).getClass().getMethod(method, null);
17                     if(sort != null && "desc".equals(sort))//倒序
18                         ret = m2.invoke(((E)b), null).toString().compareTo(m1.invoke(((E)a), null).toString());    
19                     else//正序
20                         ret = m1.invoke(((E)a), null).toString().compareTo(m2.invoke(((E)b), null).toString());
21                 }catch(NoSuchMethodException ne){
22                     System.out.println(ne);
23                 }catch(IllegalAccessException ie){
24                     System.out.println(ie);
25                 }catch(InvocationTargetException it){
26                     System.out.println(it);
27                 }
28                 return ret;
29             }
30          });
31     }
32 }

调用示例:

1 List<UserInfo> list = new ArrayList<UserInfo>();
2 //调用排序通用类
3 SortList<UserInfo> sortList = new SortList<UserInfo>();
4 //按userId排序
5 sortList.Sort(list, "getUserId", "desc");

 

posted @ 2013-12-12 09:14  Liuxiaoke  阅读(439)  评论(0)    收藏  举报