java实现对象和地图之间的转换3种方式

  

        公共静态对象mapToObject (Map<字符串,Object>地图,Class<& # 63;比;beanClass)   抛出异常{   如果(map==null)   返回null;   对象obj=beanClass.newInstance ();   org.apache.commons.beanutils.BeanUtils.populate (obj,地图);   返回obj;   }      公共静态Map<& # 63; & # 63;比;objectToMap(对象obj) {   如果(obj==null) {   返回null;   }   返回新org.apache.commons.beanutils.BeanMap (obj);   }      之前      

        公共Map<字符串,Object>{Obj2Map(对象obj)抛出异常   Object> Map<字符串;地图=new HashMap<字符串,Object> ();   .getDeclaredFields领域[]字段=obj.getClass () ();   (字段字段:字段){   field.setAccessible(真正的);   map.put (field.getName (), field.get (obj));   }   返回地图;   }   公共对象map2Obj (Map<字符串,Object>地图,Class<& # 63;比;clz)抛出异常{   对象obj=clz.newInstance ();   .getDeclaredFields领域[]declaredFields=obj.getClass () ();   字段(字段:declaredFields) {   int mod=field.getModifiers ();   如果(Modifier.isStatic (mod) | | Modifier.isFinal (mod)) {   继续;   }   field.setAccessible(真正的);   字段。集(obj map.get (field.getName ()));   }   返回obj;   }      之前      

        公共Map<字符串,Object>{obj2Map(对象obj)抛出异常   Object> Map<字符串;地图=new HashMap<字符串,Object> ();   BeanInfo BeanInfo=Introspector.getBeanInfo (obj.getClass ());   PropertyDescriptor [] propertyDescriptors=beanInfo.getPropertyDescriptors ();   (PropertyDescriptor属性:propertyDescriptors) {   字符串键=property.getName ();   如果(key.compareToIgnoreCase(“阶级”)==0){   继续;   }   getter方法=property.getReadMethod ();   对象价值=https://www.yisu.com/zixun/getter !=零?getter.invoke (obj):空;   地图。put(关键字,值);   }   返回地图;   }      公共对象map2Obj(<字符串、对象>地图,地图类<?{> clz)抛出异常   如果(map==null)   返回null;   对象obj=clz.newInstance ();   BeanInfo BeanInfo=Introspector.getBeanInfo (obj.getClass ());   PropertyDescriptor [] propertyDescriptors=beanInfo.getPropertyDescriptors ();   (PropertyDescriptor属性:propertyDescriptors) {   setter方法=property.getWriteMethod ();   如果(setter !=null) {   setter。调用(obj map.get (property.getName ()));   }   }   返回obj;   }      

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

java实现对象和地图之间的转换3种方式