java中使用反射将javaBean转为map
key : 字段名称
value: 字段值
//JavaBean转换为Map
public static Map<String, Object> beanToMap(Object bean) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
Class<?> cl = bean.getClass();
//获取指定类的BeanInfo 对象
BeanInfo beanInfo = Introspector.getBeanInfo(cl, Object.class);
//获取所有的属性描述器
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String key = pd.getName();
Method getter = pd.getReadMethod();
Object value = getter.invoke(bean);
map.put(key, value);
}
return map;
}