/**
* 將一個 JavaBean 對象轉化為一個 Map
*
* @param bean 要轉化的JavaBean 對象
* @return 轉化出來的 Map 對象
* @throws IntrospectionException 如果分析類屬性失敗
* @throws IllegalAccessException 如果實例化 JavaBean 失敗
* @throws InvocationTargetException 如果調用屬性的 setter 方法失敗
*/
public static Map convertBean(Object bean)
throws IntrospectionException, IllegalAccessException, InvocationTargetException {
Class type = bean.getClass();
Map returnMap = new HashMap();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
returnMap.put(propertyName, result);
} else {
returnMap.put(propertyName, "");
}
}
}
return returnMap;
}