// Map --> Bean 2: 利用org.apache.commons.beanutils 工具类实现 Map --> Bean public static void transMap2Bean2(Map<String, Object> map, Object obj) { if (map == null || obj == null) { return; } try { BeanUtils.populate(obj, map); } catch (Exception e) { System.out.println("transMap2Bean2 Error " + e); } } // Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean public static void transMap2Bean(Map<String, Object> map, Object obj) { try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); 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) { System.out.println("transMap2Bean Error " + e); } return; } // Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map public static Map<String, Object> transBean2Map(Object obj) { if(obj == null){ return null; } Map<String, Object> map = new HashMap<String, Object>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); // 过滤class属性 if (!key.equals("class")) { // 得到property对应的getter方法 Method getter = property.getReadMethod(); Object value = getter.invoke(obj); map.put(key, value); } } } catch (Exception e) { System.out.println("transBean2Map Error " + e); } return map; }
Java Map和Bean之前的转换
原创umgsai 博主文章分类:Java&Javaweb ©著作权
©著作权归作者所有:来自51CTO博客作者umgsai的原创作品,请联系作者获取转载授权,否则将追究法律责任

提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
将java bean转换成Map类型
将bean 转成map 类型
java servlet 开发语言 json -
Java bean 转 Map
Java bean 转 Map 时需要使用Fastjson 另外也可以使用 使用 BeanUtils 实际例子如下: 运行的代码如下: 输出的结果如下:
Javabean转Map json java json对象 对象序列化 -
xml和java Bean的直接转换,Xmap
1、XStream,XStream是codehaus上的一
java xml c++ c++程序设计 序列化 -
Map和JSON的互相转换
JSON-Lib方式 Jackson方式
Java编程 json json数据 html 数组