package com.mandi.common; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.commons.lang3.StringUtils; public class ListSortUtil { @SuppressWarnings({ "unchecked", "rawtypes" }) public void sort(List targetList, final String sortField, final String sortMode) { Collections.sort(targetList, new Comparator() { public int compare(Object obj1, Object obj2) { int retVal = 0; try { //首字母转大写 String newStr=sortField.substring(0, 1).toUpperCase()+sortField.replaceFirst("\\w",""); String methodStr="get"+newStr; Method method1 = ((T)obj1).getClass().getMethod(methodStr, null); Method method2 = ((T)obj2).getClass().getMethod(methodStr, null); if (sortMode != null && "desc".equals(sortMode)) { if(method1.invoke(((T) obj2), null)==null||method2.invoke(((T) obj1), null)==null){ retVal=1; }else { retVal = method1.invoke(((T) obj2), null).toString().compareTo(method2.invoke(((T) obj1), null).toString()); // 倒序 } } else { if(method2.invoke(((T) obj2), null)==null||method1.invoke(((T) obj1), null)==null){ retVal=-1; }else { retVal = method2.invoke(((T) obj1), null).toString().compareTo(method1.invoke(((T) obj2), null).toString()); // 正序 } } } catch (Exception e) { throw new RuntimeException(); } return retVal; } }); } @SuppressWarnings({ "unchecked", "rawtypes" }) public void sortFields(List targetList, final List sortFields) { Collections.sort(targetList, new Comparator() { public int compare(Object obj1, Object obj2) { int retVal = 0; try { for (int i=0;iInteger.parseInt(method2.invoke(((T) obj1), null).toString())){ retVal = 1; // 倒序 }else if(Integer.parseInt(method1.invoke(((T) obj2), null).toString())Double.parseDouble(method2.invoke(((T) obj1), null).toString())){ retVal = 1; // 倒序 }else if(Double.parseDouble(method1.invoke(((T) obj2), null).toString())Integer.parseInt(method2.invoke(((T) obj2), null).toString())){ retVal =1; break; }else if(Integer.parseInt(method1.invoke(((T) obj1), null).toString())Double.parseDouble(method2.invoke(((T) obj2), null).toString())){ retVal =1; break; }else if(Double.parseDouble(method1.invoke(((T) obj1), null).toString())