public List sort(List list,final String sortName,final String direction){
Collections.sort(list, new Comparator(){
public int compare(Object a, Object b){
try {
//根据属性名获取到field
Field field = a.getClass().getDeclaredField(sortName);
//field设置为public访问属性.
field.setAccessible(true);
//获取该属性的类型
Class typeClass = field.getType();
//int排序
if (typeClass.equals(Integer.class)) {
Integer one = (Integer)field.get(a);
Integer two = (Integer)field.get(b);
if ("desc".equals(direction)) {
return two - one;
} else {
return one - two;
}
} else {//String排序
String one = (String)field.get(a);
String two = (String)field.get(b);
if ("desc".equals(direction)) {
return two.compareTo(one);
} else {
return one.compareTo(two);
}
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
}
return 1;
}
});
return list;
}
}