List按照entity中某項屬性排序工具類

public class SortListUtil<T> implements Comparator<T> {
    private String  propertyName;
    private boolean isAsc;

    public SortListUtil(String propertyname, boolean isasc) {
        this.propertyName = propertyname;
        this.isAsc = isasc;
    }

    /**
     * 需要的是:根據類中的字段對對象進行排序
     *
     * @return
     */

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public int compare(T b1, T b2) {

        Class<?> clz = b1.getClass();
        Method mth = getPropertyMethod(clz, propertyName);

        try {
            Object o1 = mth.invoke(b1);
            Object o2 = mth.invoke(b2);

            if (o1 == null || o2 == null) return 0;
            Comparable value1 = (Comparable) o1;
            Comparable value2 = (Comparable) o2;

            if (isAsc) {
                return value1.compareTo(value2);
            } else {
                return value2.compareTo(value1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    // 獲取類名
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Method getPropertyMethod(Class clz, String propertyName) {
        Method mth = null;
        try {
            //實體中需要排序的屬性的get方法需要小寫屬性名稱,自動生成的首字母是大寫
            mth = clz.getMethod("get" + propertyName); 
        } catch (Exception e) {
            System.out.println("獲取類名發生錯誤!");
        }
        return mth;
    }

    public String getPropertyName() {
        return propertyName;
    }

    public void setPropertyName(String propertyName) {
        this.propertyName = propertyName;
    }

    public boolean isAsc() {
        return isAsc;
    }

    public void setAsc(boolean isAsc) {
        this.isAsc = isAsc;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章