天天看点

List集合对象排序

package com.beini.sorft;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

public class SortListUtil<T> {

public void Sort(List<T> list, final String method, final String sort) {

Collections.sort(list, new Comparator<Object>() {

public int compare(Object a, Object b) {

int ret = 0;

Method m1;

Method m2;

try {

m1 = ((T) a).getClass().getMethod(method, null);

m2 = ((T) b).getClass().getMethod(method, null);

if (sort != null && "desc".equals(sort)) {// 倒序

ret = m2.invoke(((T) b), null).toString()

.compareTo(m1.invoke(((T) a), null).toString());

} else { // 正序

ret = m1.invoke(((T) a), null).toString()

.compareTo(m2.invoke(((T) b), null).toString());

}

} catch (NoSuchMethodException e) {

e.printStackTrace();

} catch (SecurityException e) {

} catch (IllegalAccessException e) {

} catch (IllegalArgumentException e) {

} catch (InvocationTargetException e) {

}

return ret;

}

});

继续阅读