List对象排序的通用方法

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * List对象排序的通用方法
 * 
 * @author chenchuang
 * 
 * @param <E>
 */
public class ListSort<E> {
	/**
	 * 
	 * @param list 要排序的集合
	 * @param method 要排序的实体的属性所对应的get方法
	 * @param sort desc 为正序  
	 */
	public void Sort(List<E> list, final String method, final String sort) {
		// 用内部类实现排序
		Collections.sort(list, new Comparator<E>() {

			public int compare(E a, E b) {
				int ret = 0;
				try {
					// 获取m1的方法名
					Method m1 = a.getClass().getMethod(method, null);
					// 获取m2的方法名
					Method m2 = 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 (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return ret;
			}
		});
	}
}

import java.util.ArrayList;


public class ListTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ArrayList<Student> list= new ArrayList<Student>();
		list.add(new Student(1,"AA",5));
<pre name="code" class="java">		list.add(new Student(2,"BB",6));
		list.add(new Student(3,"CC",7));
  ListSort<Student> listSort= new ListSort<Student>();listSort.Sort(list, "getAge", "desc");for(Student s:list){System.out.println(s.getId()+s.getName()+s.getAge());}}}
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值