现在用 List 对象里的属性进行排序。
以下为了通用,使用了反射。
TempProductInfoEntity为临时存储的实体对象。
/**
* 暂时用来对 List 里的对象根据对象属性排序
* @author Ja0ck5
*/
public void sort(List<? extends Object> list,final String comp ,final String sort){
Collections.sort(list,new Comparator<Object>() {
public int compare(Object a,Object b) {
int result = 0;
String methodName = null;
StringBuilder sb = newStringBuilder(comp);
try {
if(StringUtil.isNotEmpty(comp)){
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
methodName=sb.insert(0, "get").toString();
Method meth1 = ((TempProductInfoEntity)a).getClass().getDeclaredMethod(methodName);
Method meth2 =((TempProductInfoEntity)a).getClass().getDeclaredMethod(methodName);
if(meth1 != null && meth2 != null){
Object compO1=meth1.invoke((TempProductInfoEntity)a);
Object compO2=meth2.invoke((TempProductInfoEntity)b);
if(compO1 !=null && compO2!=null){
if("desc".equals(sort)){
result= compO1.toString().compareTo(compO2.toString());
}else{
result= compO1.toString().compareTo(compO2.toString());
}
}
}
}
} catch (NoSuchMethodException | SecurityException e) {
throw new java.lang.RuntimeException(e);
} catch (IllegalAccessException e) {
throw new java.lang.RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new java.lang.RuntimeException(e);
} catch (InvocationTargetException e) {
throw new java.lang.RuntimeException(e);
}
return result;
}
});
}
代码略微冗余,希望看客们指点指点,只为了成为更优雅的人