javaBean與map類型相互轉換


/**
* 把Map鍵值對轉化為javaBean對象
* 
* @param type
* @param map
* @return
* @throws Exception
*/
private Object transforMapToObject(Class<? extends Object> type, Map<String, String> map) throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(type); //獲取類屬性
Object obj = type.newInstance(); //創建 JavaBean 對象
//給 JavaBean對象的屬性賦值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
try {
Object value = map.get(propertyName);
Object[] args = new Object[1];
args[0] = value;
descriptor.getWriteMethod().invoke(obj, args);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return obj;
}

/**
* 把javaBean對象轉換為Map鍵值對
* 
* @param bean
* @return
* @throws Exception
*/
private Map<String, String> transforObjectToMap(Object bean) throws Exception {
Class<? extends Object> type = bean.getClass();
Map<String, String> returnMap = new HashMap<String, String>();
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.toString());
}
}
}
return returnMap;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM