map转化bean

 1     public static <T> T mapToBean(Map<String, Object> map, Class<T> beanClass) {
 2 
 3         if (MapUtils.isEmpty(map)) {
 4             return null;
 5         }
 6 
 7         try {
 8             T t = beanClass.newInstance();
 9 
10             BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
11             PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
12             for (PropertyDescriptor property : propertyDescriptors) {
13                 Method setter = property.getWriteMethod();
14                 if (setter != null) {
15                     setter.invoke(t, map.get(property.getName()));
16                 }
17             }
18             return t;
19         } catch (Exception ex) {
20             log.error("########map集合转javabean出错######,错误信息,{}", ex.getMessage());
21             throw new RuntimeException();
22         }
23     }

 此方法主要采用了内省器,关于内省,可以看下这篇文章:

 https://www.cnblogs.com/jiangwg/articles/12252385.html

也可以使用包装好的BeanUtils方法:

https://www.cnblogs.com/jiangwg/articles/12252603.html

posted @ 2019-10-23 19:50  jiangwg  阅读(1513)  评论(0编辑  收藏  举报