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

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

/**   * 把Map键值对转化为javaBean对象   *    * @param type   * @param map   * @return   * @throws Exception   */  private Object transforMapToObject(Class
type, Map
map) throws Exception { BeanInfo beanInfo = Introspector.getBeanInfo(type); //获取类属性 Object obj = type.newInstance(); //创建 JavaBean 对象 //给 JavaBean对象的属性赋值 PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (map.containsKey(propertyName)) { try { Object value = map.get(propertyName); Object[] args = new Object[1]; args[0] = value; descriptor.getWriteMethod().invoke(obj, args); } catch (Exception e) { e.printStackTrace(); } } } return obj; } /** * 把javaBean对象转换为Map键值对 * * @param bean * @return * @throws Exception */ private Map
transforObjectToMap(Object bean) throws Exception { Class
type = bean.getClass(); Map
returnMap = new HashMap
(); BeanInfo beanInfo = Introspector.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean, new Object[0]); if (result != null) { returnMap.put(propertyName, result.toString()); } } } return returnMap; }

 

转载于:https://www.cnblogs.com/hualuoxiangxi/p/3707680.html

你可能感兴趣的文章
中国最早的CCIE__孙晖
查看>>
《Objective-C 程序设计(第4版)》书评!
查看>>
Xcode真机调试identifier not avaliable错误
查看>>
Dockerfile制作LAMP
查看>>
sublime text3安装及配置
查看>>
gitignore配置
查看>>
dell远程控制卡iDRAC如何重启?
查看>>
Mybatis-Plus 真好用(乡村爱情加持)
查看>>
信用卡相关
查看>>
Koa (koajs) 基于 Node.js 平台的下一代 web 开发框架
查看>>
ext表格grid----重写applySort方法,使支持按中文首字母排序
查看>>
使用git命令提取两次提交之间的差异文件
查看>>
node.js REPL
查看>>
面试问题
查看>>
dhcp在企业网中的应用(案例)
查看>>
nginx(7):使用nginx的proxy_cache做网站缓存
查看>>
C++ explicit
查看>>
AngularJS内置指令
查看>>
冒泡排序算法分析
查看>>
Go函数
查看>>