/**
*
*/
package com.infopatent.juangetljc.web.controller.util;
import java.lang.reflect.Field;
import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
/**
* @author xue
* 2014年9月24日
*/
public class SortListByBeanPropertyUtil {
//根据集合里的Bean拥有的属性进行排序
public static <T> void sort(List<T> list, final String sortProperty, final String sort) {
if(list == null || sortProperty == null || "".equals(sortProperty) || list.isEmpty())
return;
Collections.sort(list, new Comparator<T>() {
@Override
public int compare(T t1, T t2) {
Object o1 = new Object();
Object o2 = new Object();
try {
o1 = SortListByBeanPropertyUtil.getFieldValue(t1, sortProperty);
o2 = SortListByBeanPropertyUtil.getFieldValue(t2, sortProperty);
} catch (Exception e) {
e.printStackTrace();
}
int result = 0;
if(o1 == null) {
result = -1;
}else if(o2 == null) {
result = 1;
}else if(o1 instanceof String) {
result = Collator.getInstance(Locale.CHINESE).compare(o1, o2);
}else{
result = ((Comparable)o1).compareTo(o2);
}
//是否降序排序
if("desc".equalsIgnoreCase(sort)) {
result = 0-result;
}
return result;
}
});
}
//反射方法,反射出类型
public static Object getFieldValue(Object obj, String fieldName) throws Exception {
//反射出对象类型
Class<?> cls = obj.getClass();
//反射出类型字段
Field field = cls.getDeclaredField(fieldName);
//获取属性是,压制java对访问修饰符的检查
field.setAccessible(true);
//在对象obj上读取field属性的值
Object val = field.get(obj);
return val;
}
}
posted on 2014-09-24 16:25
小人物_Amor 阅读(334)
评论(0) 编辑 收藏 所属分类:
java