/**
* 排序方法
* @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;
}
});
}
要是没有get方法 可以用用字段反射获取对应值 至于怎么写自己查去网上一堆 唯一注意的是获取private属性值是要先开启访问权限 实际上setAccessible是启用和禁用访问安全检查的开关
值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查
setAccessible(true)
设置访问权限 不止是字段 方法也是同样的
method.setAccessible(true);
field.setAccessible(true);