/**
* 排序方法
* @param targetList 要排序的对象
* @param sortField 用哪个字段排序
* @param sortMode 倒序desc还是正序asc
*/
@SuppressWarnings("unchecked")
public static void sort(List<Object> targetList, String sortField, String sortMode) {
//使用集合的sort方法 ,并且自定义一个排序的比较器
Collections.sort(targetList, new Comparator<Object>() {
//匿名内部类,重写compare方法
public int compare(Object obj1, Object obj2) {
int result = 0;
try {
//首字母转大写
String newStr = sortField.substring(0, 1).toUpperCase()+sortField.replaceFirst("\\w","");
//获取需要排序字段的“get方法名”
String methodStr = "get"+newStr;
/** API文档::
* getMethod(String name, Class<?>... parameterTypes)
* 返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。
*/
Method method1 = obj1.getClass().getMethod(methodStr, null);
Method method2 = obj2.getClass().getMethod(methodStr, null);
Object returnObj1 = method1.invoke((obj1), null);
Object returnObj2 = method2.invoke((obj2), null);
result = (Integer)returnObj1 - (Integer)returnObj2;
} catch (Exception e) {
throw new RuntimeException();
}
if ("desc".equals(sortMode)) {
// 倒序
result = -result;
}
return result;
}
});
}
list中不同实体 根据相同字段排序
猜你喜欢
转载自blog.csdn.net/qq_35653822/article/details/82557342
今日推荐
周排行