如果可能的话,如何将反射从该循环中拉出并传入 getter 方法。
public <E> void sortBy(final String fieldName, final boolean sortAsc, List<E> list){
Collections.sort(list, new Comparator<E>() {
public int compare(E o1, E o2) {
return compareFields(o1,o2,fieldName.replace("SortBy", "get"),sortAsc);
}
}
);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected <E> int compareFields(E o1, E o2,String fieldName, boolean sortAsc){
try {
Comparable o1Data;
Comparable o2Data;
o1Data = (Comparable) o1.getClass().getMethod(fieldName).invoke(o1);
o2Data = (Comparable) o2.getClass().getMethod(fieldName).invoke(o2);
if(o1Data == null && o2Data == null){
return 0;
} else if (o1Data == null){
return 1;
} else if (o2Data == null){
return -1;
}
int result = o2Data.compareTo(o1Data);
return (sortAsc) ? -result : result ;
}
catch(Exception e) {
throw new RuntimeException(e);
}
}
上下文:我有很多带有数据表的屏幕。每个都是从列表构建的。每个数据表都需要可按其 6 列中的每一列进行排序。这些列是日期或字符串。
最佳答案
如果你可以假设所有元素都是相同的类型。
public <E> void sortBy(final String fieldName, final boolean sortAsc, List<E> list) throws NoSuchMethodException {
final Method f = list.get(0).getClass().getMethod(fieldName.replace("SortBy", "get"));
f.setAccessible(true);
final int direction = sortAsc ? +1 : -1;
Collections.sort(list, new Comparator<E>() {
public int compare(E o1, E o2) {
return compareFields(o1, o2, f, direction);
}
}
);
}
@SuppressWarnings({"rawtypes", "unchecked"})
protected <E> int compareFields(E o1, E o2, Method getter, int sortAsc) {
try {
Comparable o1Data = (Comparable) getter.invoke(o1);
Comparable o2Data = (Comparable) getter.invoke(o2);
if (o1Data == null)
return o2Data == null ? 0 : 1;
if (o2Data == null)
return -1;
return sortAsc * o2Data.compareTo(o1Data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
关于java - 如何从这个循环中提取反射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8885634/