泛型实现通用对象工具类(3)

3 篇文章 0 订阅
3 篇文章 0 订阅
    整理一下自己写的通用工具类,项目中用到比较多,代码如下:

/**
 * 把集合中的对象能够以其属性以键值对(k->v)的形式返回的工具类
 * @author dengjingsi
 */
public class BeanMapUtil {
    /**
     * 把集合能够以其属性以键值对(k->v)
     * @param list
     * @param propertyKey 最为K的获取属性的方法名
     * @param propertyValue 最为V的获取属性的方法名
     * @param <T> 类元素
     * @param <K> 作为key的类的属性类型
     * @param <V> 作为value的类的属性类型
     * @return
     */
    public static <T,K,V> Map<K,V> formatProperty(List<T> list, String propertyKey, String propertyValue){
        if(null == list || list.size() == 0){
            return new HashMap<>(0);
        }
        Map<K,V> map = new HashMap<>(list.size());
        try{
            for(T element : list){
                Method methodKey = element.getClass().getMethod(propertyKey,new Class[]{});
                Method methodValue = element.getClass().getMethod(propertyValue,new Class[]{});
                map.put((K)methodKey.invoke(element,new Object[]{}),(V)methodValue.invoke(element));
            }
        }catch(NoSuchMethodException n){
            n.printStackTrace();
        }catch(InvocationTargetException it){
            it.printStackTrace();
        }catch(IllegalAccessException i){
            i.printStackTrace();
        }
        return map;
    }

    /**
     * 把集合能够以其属性以键值对(k->v)默认K为getId
     * @param list
     * @param propertyValue
     * @param <T> 类元素
     * @param <K> 作为key的类的属性类型
     * @param <V> 作为value的类的属性类型
     * @return
     */
    public static <T,K,V> Map<K,V> formatProperty(List<T> list,String propertyValue){
        return formatProperty(list,"getId",propertyValue);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值