博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java对象与map对象相互转换
阅读量:7088 次
发布时间:2019-06-28

本文共 2857 字,大约阅读时间需要 9 分钟。

 

/**  * 使用org.apache.commons.beanutils进行转换  */  class A {            public static Object mapToObject(Map
map, Class
beanClass) throws Exception { if (map == null) return null; Object obj = beanClass.newInstance(); org.apache.commons.beanutils.BeanUtils.populate(obj, map); return obj; } public static Map
objectToMap(Object obj) { if(obj == null) return null; return new org.apache.commons.beanutils.BeanMap(obj); } } /** * 使用Introspector进行转换 */ class B { public static Object mapToObject(Map
map, Class
beanClass) throws Exception { if (map == null) return null; Object obj = beanClass.newInstance(); BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { Method setter = property.getWriteMethod(); if (setter != null) { setter.invoke(obj, map.get(property.getName())); } } return obj; } public static Map
objectToMap(Object obj) throws Exception { if(obj == null) return null; Map
map = new HashMap
(); BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (key.compareToIgnoreCase("class") == 0) { continue; } Method getter = property.getReadMethod(); Object value = getter!=null ? getter.invoke(obj) : null; map.put(key, value); } return map; } } /** * 使用reflect进行转换 */ class C { public static Object mapToObject(Map
map, Class
beanClass) throws Exception { if (map == null) return null; Object obj = beanClass.newInstance(); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { int mod = field.getModifiers(); if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){ continue; } field.setAccessible(true); field.set(obj, map.get(field.getName())); } return obj; } public static Map
objectToMap(Object obj) throws Exception { if(obj == null){ return null; } Map
map = new HashMap
(); Field[] declaredFields = obj.getClass().getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); map.put(field.getName(), field.get(obj)); } return map; } }

 

转载地址:http://fnfql.baihongyu.com/

你可能感兴趣的文章
android adb命令行工具使用
查看>>
[转]聊聊.net程序设计——浅谈使用VS2010建模拓展
查看>>
Central Europe Regional Contest 2011
查看>>
每天一个linux命令(12):more命令
查看>>
javascript 正则替换字符的新方法!
查看>>
OSGI:从面向接口编程来理解OSGI
查看>>
前端之JavaScript(1) - 浅谈JavaScript函数与栈
查看>>
WayOs 帐号到期自动清理工具,致浪费在清理到期用户的青春
查看>>
新买的mac笔记本,发现vi编辑器没有颜色的解决方案
查看>>
object-c 混编 调用C,C++接口
查看>>
JQuery Ajax实例总结
查看>>
CentOS中文件夹基本操作命令
查看>>
VS2008 Project : error PRJ0019: 某个工具从以下位置返回了错误代码: "正在执行生成后事件..."解决方案...
查看>>
js判断图片是否存在,并做处理
查看>>
触摸屏
查看>>
webservice 测试窗体只能用于来自本地计算机的请求
查看>>
Java 中队列的使用
查看>>
再见 2014,你好 2015
查看>>
13 SELECT 以外的内容
查看>>
初中面谈招生网上招生报名系统
查看>>