在調用第三方接口發現對方使用map進行接收(不包括秘鑰等),將bean類屬性轉換為map,直接貼代碼:
/**
* JavaBean對象轉化成Map對象
*
* @param javaBean
*/
public static Map java2Map(Object javaBean) {
Map map = new HashMap(16);
try {
// 獲取javaBean屬性
BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
if (propertyDescriptors != null && propertyDescriptors.length > 0) {
String propertyName = null; // javaBean屬性名
Object propertyValue = null; // javaBean屬性值
for (PropertyDescriptor pd : propertyDescriptors) {
propertyName = pd.getName();
if (!propertyName.equals("class")) {
Method readMethod = pd.getReadMethod();
propertyValue = readMethod.invoke(javaBean, new Object[0]);
map.put(propertyName, propertyValue);
}
}
}
} catch (Exception e) {
logger.error("javaBean轉換map失敗!",e);
//注意:日志最好不要使用 e.printStackTrace();如果打印日志過多,會引起死鎖.
}
return map;
}