我希望我的列表将根据Date
变量进行排序,所以我必须编写这个逻辑
public static void main(String a[]){
AuditLogComponent comp = new AuditLogComponent();
List<TableRecord> records = new ArrayList<TableRecord>();
LogFolderRecord log = new LogFolderRecord();
Date date = new Date();
Timestamp fromTS1 = new Timestamp(date.getTime());
log.setStampDate(fromTS1);
records.add(log);
Date date1 = new Date();
Timestamp fromTS2 = new Timestamp(date1.getTime());
LogFolderRecord log1 = new LogFolderRecord();
log1.setStampDate(fromTS2);
records.add(log1);
records.add(new LogPeopleRecord());
comp.columnsList(records);
}
以及我如何调用 List 的 Sort 方法
public void columnsList(List<TableRecord> records){
Collections.sort(records, new StampDateComparator());
for(TableRecord record : records){
Table table = record.getTable();
Field[] fields = table.fields();
for(Field field : fields){
field.getName();
record.getValue(field);
}
}
}
我的 Comparator 类是
public class StampDateComparator implements Comparator<Object> {
@Override
public int compare(Object object1, Object object2) {
try {
Method method = object1.getClass().getDeclaredMethod("getStampDate");
Date value = (Date) method.invoke(object1);
Method method1 = object1.getClass().getDeclaredMethod("getStampDate");
Date value1 = (Date) method.invoke(object2);
if(value != null && value1 != null )
return value.compareTo(value1);;
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
但它不会抛出异常
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.csdcsystems.amanda.comp.macro.StampDateComparator.compare(StampDateComparator.java:22)
at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
根据日期进行排序的确切方法是什么?