天天看點

将xml的model 節點屬性轉化為Map , 再将Map 轉為javaBen

2。将map轉換成bean

3.// 将javaBean 轉化為 Map

[code]

private static <T> Map<Object, Object> convertBeanToMap(Object bean)

throws IntrospectionException {

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();

try {

Object result = readMethod.invoke(bean, new Object[0]);

returnMap.put(propertyName, result);

} catch (Exception e) {

// TODO Auto-generated catch block

logger.debug("解析方法名:" + readMethod + ",有誤!");

// e.printStackTrace();

}

}

}

return returnMap;

}

// 将Map轉化為javaBean

private static <T> T convertMapToBean(Class<T> type, Map<Object, Object> map)

throws IntrospectionException, InstantiationException,

IllegalAccessException {

BeanInfo beanInfo = Introspector.getBeanInfo(type); // 擷取類屬性

T t = type.newInstance(); // 建立 JavaBean 對象

// 給 JavaBean 對象的屬性指派

for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {

String propertyName = descriptor.getName();

if (map.containsKey(propertyName)) {

// 下面一句可以 try 起來,這樣當一個屬性指派失敗的時候就不會影響其他屬性指派。

String value = ConvertUtils.convert(map.get(propertyName));

Object[] args = new Object[1];

try {

args[0] = df.parse(value);

} catch (ParseException e) {

args[0] = ConvertUtils.convert(value,

descriptor.getPropertyType());

}

try {

descriptor.getWriteMethod().invoke(t, args);

} catch (IllegalArgumentException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InvocationTargetException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

return t;

}

}

[/code]