java实现Object和Map之间的转换3种方式
利用commons.BeanUtils实现Obj和Map之间转换,这种是最简单,也是最经常用的
publicstaticObjectmapToObject(Mapmap,Class>beanClass) throwsException{ if(map==null) returnnull; Objectobj=beanClass.newInstance(); org.apache.commons.beanutils.BeanUtils.populate(obj,map); returnobj; } publicstaticMap,?>objectToMap(Objectobj){ if(obj==null){ returnnull; } returnneworg.apache.commons.beanutils.BeanMap(obj); }
利用javareflect完成Obj和Map之间的相互转换
publicMapObj2Map(Objectobj)throwsException{ Map map=newHashMap (); Field[]fields=obj.getClass().getDeclaredFields(); for(Fieldfield:fields){ field.setAccessible(true); map.put(field.getName(),field.get(obj)); } returnmap; } publicObjectmap2Obj(Map map,Class>clz)throwsException{ Objectobj=clz.newInstance(); Field[]declaredFields=obj.getClass().getDeclaredFields(); for(Fieldfield:declaredFields){ intmod=field.getModifiers(); if(Modifier.isStatic(mod)||Modifier.isFinal(mod)){ continue; } field.setAccessible(true); field.set(obj,map.get(field.getName())); } returnobj; }
利用Introspector完成Obj和Map之间的相互转换
publicMapobj2Map(Objectobj)throwsException{ Map map=newHashMap (); BeanInfobeanInfo=Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[]propertyDescriptors=beanInfo.getPropertyDescriptors(); for(PropertyDescriptorproperty:propertyDescriptors){ Stringkey=property.getName(); if(key.compareToIgnoreCase("class")==0){ continue; } Methodgetter=property.getReadMethod(); Objectvalue=getter!=null?getter.invoke(obj):null; map.put(key,value); } returnmap; } publicObjectmap2Obj(Map map,Class>clz)throwsException{ if(map==null) returnnull; Objectobj=clz.newInstance(); BeanInfobeanInfo=Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[]propertyDescriptors=beanInfo.getPropertyDescriptors(); for(PropertyDescriptorproperty:propertyDescriptors){ Methodsetter=property.getWriteMethod(); if(setter!=null){ setter.invoke(obj,map.get(property.getName())); } } returnobj; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短