`

Java中对象(Object)转换成Map

阅读更多

以前没用过此类方法

1.最简单的转换方法

com.sun.org.apache.commons.beanutils.BeanUtils;

Map map1= new HashMap();

map1 = BeanUtils.describe(要转换的对象);  

 

2.此处转自其它博客,可以参考里面DynaProperty的用法

 


package org.apache.commons.beanutils;
import java.beans.PropertyDescriptor; 
import java.lang.reflect.InvocationTargetException; 
import java.util.HashMap; 
import java.util.Map;

/** 
* 
* @since 1.0 
*/ 
public class PageBeanUtilsBean extends BeanUtilsBean { 
@Override 
public Map<String, Object> describe(Object bean) throws IllegalAccessException, InvocationTargetException, 
NoSuchMethodException {

if (bean == null) { 
//            return (Collections.EMPTY_MAP); 
return (new java.util.HashMap<String, Object>()); 
} 
Map<String, Object> description = new HashMap<String, Object>(); 
if (bean instanceof DynaBean) { 
DynaProperty[] descriptors = ((DynaBean) bean).getDynaClass().getDynaProperties(); 
for (int i = 0; i < descriptors.length; i++) { 
String name = descriptors[i].getName(); 
description.put(name, getProperty(bean, name)); 
} 
} else { 
PropertyDescriptor[] descriptors = getPropertyUtils().getPropertyDescriptors(bean); 
Class clazz = bean.getClass(); 
for (int i = 0; i < descriptors.length; i++) { 
String name = descriptors[i].getName(); 
if (getPropertyUtils().getReadMethod(clazz, descriptors[i]) != null) { 
description.put(name, getPropertyUtils().getNestedProperty(bean, name)); 
} 
} 
} 
return (description);

} 
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics