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

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dengjingsi
 * 格式化工具類
 * S爲需要作爲主鍵的類型map的key類型(T中的一個屬性類型),T爲map的value值
 */
public class FormatUtil<S,T> {

    /**
     * 把list格式的對象以property方法名獲取到的屬性爲主鍵,轉化爲map格式
     * @param list
     * @param property
     * @return
     */
    public Map<S,T> formatList(List<T> list, String property){
        if(null == list || list.size() == 0){
            return new HashMap<>(0);
        }
        Map<S,T> map = new HashMap<>(list.size());
        try{
            for(T element : list){
                Method method = element.getClass().getMethod(property,new Class[]{});
                map.put((S)method.invoke(element,new Object[]{}),element);
            }
        }catch(NoSuchMethodException n){
            n.printStackTrace();
        }catch(InvocationTargetException it){
            it.printStackTrace();
        }catch(IllegalAccessException i){
            i.printStackTrace();
        }
        return map;
    }

    /**
     * 把list格式的對象以Id屬性爲主鍵,轉化爲map格式
     * @param list
     * @return
     */
    public Map<S,T> formatList(List<T> list){
        return formatList(list, "getId");
    }

    /**
     * 把list集合以R對象的getProperty方法名獲取到的屬性爲key、R爲value,生成map集合
     * @param list R的list集合
     * @param getProperty 獲取key屬性方法名
     * @param <E> key屬性的類型
     * @param <R> 元素
     * @return R以getProperty方法獲取到的值爲key的map集合
     */
    public static <E,R> Map<E,R> get(List<R> list,String getProperty){
        Map<E,R> map = new HashMap<>(list.size());
        for(R element : list){
            Method method = null;
            try {
                method = element.getClass().getMethod(getProperty,new Class[]{});
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            try {
                map.put((E)method.invoke(element,new Object[]{}),element);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}

泛型實現通用對象工具類:https://blog.csdn.net/weixin_39194257/article/details/88736394

針對自己寫的泛型工具類方法,新增public static <E,R> Map<E,R> get(List<R> list,String getProperty)方法,針對方法的泛型,運用更靈活,就不需要實例化工具類對象了。

 

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