List<entity>按照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;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值