} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (sort != null && sort.toLowerCase().equals(DESC)) {
return -ret;
} else {
return ret;
}
}
});
}
}
return list;
}
/**
* 默认按正序排列
*
* @param list
* @param method
* @return
*/
public static List<?> sortByMethod(List<?> list, final String method) {
return sortByMethod(list, method, null);
}
@SuppressWarnings("unchecked")
public static List<?> sortByMethod(List<?> list, final String method,
final String sort) {
Collections.sort(list, new Comparator() {
public int compare(Object a, Object b) {
int ret = 0;
try {
Method m = a.getClass().getMethod(method, null);
m.setAccessible(true);
Class<?> type = m.getReturnType();
if (type == int.class) {
ret = ((Integer) m.invoke(a, null))
.compareTo((Integer) m.invoke(b, null));
} else if (type == double.class) {
ret = ((Double) m.invoke(a, null)).compareTo((Double) m
.invoke(b, null));
} else if (type == long.class) {
ret = ((Long) m.invoke(a, null)).compareTo((Long) m
.invoke(b, null));
} else if (type == float.class) {
ret = ((Float) m.invoke(a, null)).compareTo((Float) m
.invoke(b, null));
} else if (type == Date.class) {
ret = ((Date) m.invoke(a, null)).compareTo((Date) m
.invoke(b, null));
} else if (isImplementsOf(type, Comparable.class)) {
ret = ((Comparable) m.invoke(a, null))
.compareTo((Comparable) m.invoke(b, null));
} else {
ret = String.valueOf(m.invoke(a, null)).compareTo(
String.valueOf(m.invoke(b, null)));
}