Map转Bean小工具

public static <T> T converter(Map<String, Object> map, Class<T> clz) {
    T obj = null;
    try {
        obj = clz.newInstance();
        BeanInfo beanInfo = Introspector.getBeanInfo(clz);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (map.containsKey(key)) {
                Object value = map.get(key);
                // 得到property对应的setter方法
                Method setter = property.getWriteMethod();
                setter.invoke(obj, value);
            }
        }
    } catch (Exception e) {
        logger.error("map转{}异常", clz.getName(), e);
    }
    return obj;
}

  

 

public static <T> List<T> converter(List<Map<String, Object>> list, Class<T> clz) {
    List<T> rst = new ArrayList<>();
    for (int i = 0; i < list.size(); i++) {
        rst.add(converter(list.get(i), clz));
    }
    return rst;
}

  

posted @ 2015-08-30 10:46  狂奔的小狮子  阅读(310)  评论(0编辑  收藏  举报