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 出阁宴祝福语姐姐简短