java实现Object和Map之间的转换3种方式
程序员文章站
2023-12-04 15:18:11
利用commons.beanutils实现obj和map之间转换,这种是最简单,也是最经常用的
public static object maptoobject(...
利用commons.beanutils实现obj和map之间转换,这种是最简单,也是最经常用的
public static object maptoobject(map<string, object> map, class<?> beanclass) throws exception { if (map == null) return null; object obj = beanclass.newinstance(); org.apache.commons.beanutils.beanutils.populate(obj, map); return obj; } public static map<?, ?> objecttomap(object obj) { if (obj == null) { return null; } return new org.apache.commons.beanutils.beanmap(obj); }
利用java reflect完成obj和map之间的相互转换
public map<string,object> obj2map(object obj) throws exception{ map<string,object> map=new hashmap<string, object>(); field[] fields = obj.getclass().getdeclaredfields(); for(field field:fields){ field.setaccessible(true); map.put(field.getname(), field.get(obj)); } return map; } public object map2obj(map<string,object> map,class<?> clz) throws exception{ object obj = clz.newinstance(); field[] declaredfields = obj.getclass().getdeclaredfields(); for(field field:declaredfields){ int mod = field.getmodifiers(); if(modifier.isstatic(mod) || modifier.isfinal(mod)){ continue; } field.setaccessible(true); field.set(obj, map.get(field.getname())); } return obj; }
利用introspector完成obj和map之间的相互转换
public map<string,object> obj2map(object obj) throws exception{ map<string,object> map=new hashmap<string, object>(); beaninfo beaninfo = introspector.getbeaninfo(obj.getclass()); propertydescriptor[] propertydescriptors = beaninfo.getpropertydescriptors(); for (propertydescriptor property : propertydescriptors) { string key = property.getname(); if (key.comparetoignorecase("class") == 0) { continue; } method getter = property.getreadmethod(); object value = getter!=null ? getter.invoke(obj) : null; map.put(key, value); } return map; } public object map2obj(map<string,object> map,class<?> clz) throws exception{ if (map == null) return null; object obj = clz.newinstance(); beaninfo beaninfo = introspector.getbeaninfo(obj.getclass()); propertydescriptor[] propertydescriptors = beaninfo.getpropertydescriptors(); for (propertydescriptor property : propertydescriptors) { method setter = property.getwritemethod(); if (setter != null) { setter.invoke(obj, map.get(property.getname())); } } return obj; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。