反射排序
public <T> List<T> sortObject(List<T> list, Class<T> entityClass, String field) throws NoSuchMethodException,SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
boolean isAllNumber = true;
String methodName = "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
Method method = entityClass.getMethod(methodName, null);
List<String> strList = new ArrayList<>();
if (list == null)
return null;
for (T t : list) {
strList.add((String) method.invoke(t, null));
}
for (String str : strList) {
if (!str.matches("^\\d+$")) {
isAllNumber = false;
}
}
if (isAllNumber) {
list.sort((Comparator<? super T>) new Comparator<T>() {
@Override
public int compare(T t1, T t2) {
try {
String o1 = (String) method.invoke(t1, null);
String o2 = (String) method.invoke(t2, null);
return Double.valueOf(o1).compareTo(Double.valueOf(o2));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
});
} else {
list.sort((Comparator<? super T>) new Comparator<T>() {
@Override
public int compare(T t1, T t2) {
try {
String o1 = (String) method.invoke(t1, null);
String o2 = (String) method.invoke(t2, null);
return o1.compareTo(o2);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
});
}
return null;
}
来源于当时要对几种类似的列表进行同样的排序——如果此字段全是数字,按照数字排序;否则都按字符串排序。当然还有许多要改进的地方,比如entityClass可以在此段代码获取,没有传order direction等。