栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Javabean和map相互转化方法代码示例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Javabean和map相互转化方法代码示例

在做导入的时候,遇到了需要将map对象转化 成javabean的问题,也就是说,不清楚javabean的内部字段排列,只知道map的 key代表javabean的字段名,value代表值。

那现在就需要用转化工具了。是通用的哦!

首先来看 JavaBean 转化成Map的方法:

 
 @SuppressWarnings({ "rawtypes", "unchecked" }) 
 public static Map convertBean(Object bean) 
   throws IntrospectionException, IllegalAccessException, InvocationTargetException { 
  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); 
    } else { 
     returnMap.put(propertyName, ""); 
    } 
   } 
  } 
  return returnMap; 
 } 

下面是将Map转化成JavaBean对象的方法:

 
 @SuppressWarnings("rawtypes") 
 public static Object convertMap(Class type, Map map) 
   throws IntrospectionException, IllegalAccessException, 
   InstantiationException, InvocationTargetException { 
  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); 
   } 
  } 
  return obj; 
 } 

以上内容我测试过,是没有问题的,供大家参考学习。感谢大家对本站的支持。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/144328.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号