java实现Object和Map之间的转换3种⽅式利⽤commons.BeanUtils实现Obj和Map之间转换,这种是最简单,也是最经常⽤的
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass)
throws Exception {
if (map == null)
return null;
Object obj = wInstance();
org.apachemons.beanutils.BeanUtils.populate(obj, map);
return obj;
}
public static Map<?, ?> objectToMap(Object obj) {
if (obj == null) {
return null;
}
return new org.apachemons.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 = Class().getDeclaredFields();
for(Field field:fields){
field.setAccessible(true);
map.Name(), (obj));
}
return map;
}
public Object map2Obj(Map<String,Object> map,Class<?> clz) throws Exception{
Object obj = wInstance();
Field[] declaredFields = Class().getDeclaredFields();
for(Field field:declaredFields){
int mod = Modifiers();
if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
continue;
}
field.setAccessible(true);
field.set(obj, (Name()));
}
return obj;
}
利⽤Introspector完成Obj和Map之间的相互转换
public Map<String,Object> obj2Map(Object obj) throws Exception{
Map<String,Object> map=new HashMap<String, Object>();
BeanInfo beanInfo = Class());
object toPropertyDescriptor[] propertyDescriptors = PropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = Name();
if (keypareToIgnoreCase("class") == 0) {
continue;
}
Method getter = ReadMethod();
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 = wInstance();
BeanInfo beanInfo = Class());
PropertyDescriptor[] propertyDescriptors = PropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = WriteMethod();
if (setter != null) {
setter.invoke(obj, (Name()));
}
}
return obj;
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论