//将javabean实体类转为map类型,然后返回一个map类型的值
public static Map beanToMap(Object obj) {
Map params = new HashMap(0);
try {
PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
for (int i = 0; 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的网址分别是:
注意:
如果只引用了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.(ConvertUtilsBean.java:157) at org.apache.commons.beanutils.BeanUtilsBean.(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)