当前位置: 移动技术网 > IT编程>开发语言>Java > Javabean和map相互转化方法代码示例

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

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

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

首先来看 javabean 转化成map的方法:

[java] 
/**
   * 将一个 javabean 对象转化为一个 map
   * @param bean 要转化的javabean 对象
   * @return 转化出来的 map 对象
   * @throws introspectionexception 如果分析类属性失败
   * @throws illegalaccessexception 如果实例化 javabean 失败
   * @throws invocationtargetexception 如果调用属性的 setter 方法失败
   */ 
  @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对象的方法:

[java] 
/**
   * 将一个 map 对象转化为一个 javabean
   * @param type 要转化的类型
   * @param map 包含属性值的 map
   * @return 转化出来的 javabean 对象
   * @throws introspectionexception 如果分析类属性失败
   * @throws illegalaccessexception 如果实例化 javabean 失败
   * @throws instantiationexception 如果实例化 javabean 失败
   * @throws invocationtargetexception 如果调用属性的 setter 方法失败
   */ 
  @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; 
  } 

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网