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]