码迷,mamicode.com
首页 > 其他好文 > 详细

Map转Bean小工具

时间:2015-08-30 11:11:33      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

  

Map转Bean小工具

标签:

原文地址:http://www.cnblogs.com/spring87/p/4770435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!