现在的位置: 首页 > 综合 > 正文

控制LIST<>根据对象字段自然排序

2014年09月07日 ⁄ 综合 ⁄ 共 1360字 ⁄ 字号 评论关闭

package org.Transform;

import java.lang.reflect.Method; 
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.List; 
 
public class SortList<E> { 
 
    @SuppressWarnings("unchecked") 
    public void sortList(List list, final String method, final String sort) { 
 
        final String name = "get" + method.substring(0, 1).toUpperCase() 
                + method.substring(1); 
 
        Collections.sort(list, new Comparator() { 
 
            public int compare(Object a, Object b) { 
                int i = 0; 
                try { 
                    Method m1 = ((E) a).getClass().getMethod(name, null); 
                    Method m2 = ((E) b).getClass().getMethod(name, null); 
                    Object o1 = m1.invoke(((E) a), null); 
                    Object o2 = m2.invoke(((E) b), null); 
                    i = compareTo(o1.getClass(), o1, o2); 
                } catch (Exception e) { 
                    System.err.println(e.getMessage()); 
                } 
                return i; 
            } 
 
        });         
 
    } 
 
    public int compareTo(Class c, Object a, Object b) { 
        if (c == Integer.class) { 
            return ((Integer) a).compareTo((Integer) b); 
        } else if (c == Long.class) { 
            return ((Long) a).compareTo((Long) b); 
        } else if (c == Double.class) { 
            return ((Double) a).compareTo((Double) b); 
        } else if (c == Short.class) { 
            return ((Short) a).compareTo((Short) b); 
        } else if (c == Float.class) { 
            return ((Float) a).compareTo((Float) b); 
        } else {             
            return (a.toString().compareTo(b.toString())); 
        } 
    } 
}

抱歉!评论已关闭.