packagecn.itcast.itcastweb.web.servlets;importjava.lang.reflect.Method;importjava.text.SimpleDateFormat;import java.util.*;public class ListComparator implementsComparator {publicListComparator() {
}publicListComparator(String methodName) {this.methodName =methodName;
}//空:普通的数据类型 非空:对象数据类型 取methodName返回值比较
String methodName;public Object getValue(Object bean, String methodName) throwsException {
Method getMethod= bean.getClass().getMethod(methodName, null);return getMethod.invoke(bean, null);
}public intcompare(Object obj1, Object obj2) {int val = -1;try{if (methodName == null) {
val=_compare(obj1, obj2);
}else{
val=_compare(getValue(obj1, methodName),
getValue(obj2, methodName));
}
}catch(Exception ex) {
ex.printStackTrace();
}returnval;
}public int _compare(Object obj1, Object obj2) throwsException {if (obj1 == null || obj2 == null)return obj1 == null ? -1 : 1;
Class cl=obj1.getClass();if (obj1 instanceofjava.lang.Comparable) {//byte int long float..number, date , boolean , char
Method getMethod = obj1.getClass().getMethod("compareTo",newClass[] { cl });return (Integer) getMethod.invoke(obj1, newObject[] { obj2 });
}return -1;
}
}//测试类
classListComparator {
Long id;publicLong getId() {returnid;
}public voidsetId(Long id) {this.id =id;
}public static voidmain(String[] args) {//普通数据类型 升序
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
List list= newArrayList();for (long i = 0; i < 5; i++) {
list.add(newDate(System.currentTimeMillis()+ (int) (Math.random() * 1000000000)));
}
ListComparator c= newListComparator();
Collections.sort(list, c);for (int i = 0; i < list.size(); i++) {
System.out.println(simpleDateFormat.format(list.get(i)));
}//对象数据类型 降序
List userList = newArrayList();
ListComparator test= newListComparator();
test.setId(null);
userList.add(test);for (long i = 0; i < 5; i++) {
test= newListComparator();
test.setId(i);
userList.add(test);
}
c= new ListComparator("getId");
Collections.sort(userList, Collections.reverseOrder(c));for (int i = 0; i < userList.size(); i++) {
System.out.println(userList.get(i).getId());
}
}
}