javabean实体类对象转为Map类型对象的方法(转发)

//将javabean实体类转为map类型,然后返回一个map类型的值
public static Map<String, Object> beanToMap(Object obj) {
Map<String, Object> params = new HashMap<String, Object>(0);
try {
PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
for (int i = 0; i < descriptors.length; i++) {
String name = descriptors[i].getName();
if (!"class".equals(name)) {
params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return params;
}

放入上面方法的类需要 import java.beans.PropertyDescriptor;

需要引用两个jar包:commons-beanutils-1.9.2.jar   commons-logging-1.2.jar

获取上面两个jar的网址分别是:http://commons.apache.org/beanutils/   http://commons.apache.org/proper/commons-logging/

注意:

如果只引用了commons-beanutils-1.9.2.jar 未引用 commons-beanutils-1.9.2.jar,控制台会报以下错误:

Exception in thread "main" java.lang.NoClassDefFoundError:org/apache/commons/logging/LogFactory
 at org.apache.commons.beanutils.ConvertUtilsBean.<init>(ConvertUtilsBean.java:157)
 at org.apache.commons.beanutils.BeanUtilsBean.<init>(BeanUtilsBean.java:117)
 at org.apache.commons.beanutils.BeanUtilsBean$1.initialValue(BeanUtilsBean.java:68)
 at org.apache.commons.beanutils.ContextClassLoaderLocal.get(ContextClassLoaderLocal.java:153)
 at org.apache.commons.beanutils.BeanUtilsBean.getInstance(BeanUtilsBean.java:80)
 at org.apache.commons.beanutils.BeanUtils.getProperty(BeanUtils.java:382)
 at fighting.IntroSpectorDemo.main(IntroSpectorDemo.java:31)

原文链接:http://www.cnblogs.com/shifei/p/4584724.html

ps : 侵删。

上一篇:spring的2种类型转换器


下一篇:阿里云申请ssl证书配置tomcat访问https