泛型實現通用對象工具類(3)

    整理一下自己寫的通用工具類,項目中用到比較多,代碼如下:

/**
 * 把集合中的對象能夠以其屬性以鍵值對(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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章