MapToBean
上篇我们讲到了,mapToBean所遇到了问题,"argument type mismatch"参数类型不匹配
到底是怎么解决它呢?
我也思考了良久,最后在常用的包装数据类中发现了一处规律。
瞧!
它们都有参数为字符串类型的构造函数,我就想利用这种构造函数来搞点事情。
于是我在上一篇博客“Java小程序之MapToBean之一”的代码中,加了点革命性的代码。
事实证明,我的idea是对的,它成功了!为自己喝彩,鼓掌!!!
附上代码
package com.liurui.test;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class MyUtility {
public static <LiuRui> LiuRui mapToBean(Map<String, Object> map, LiuRui liuRui) throws IntrospectionException, InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException {
BeanInfo beanInfo = Introspector.getBeanInfo(liuRui.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
Method writeMethod;
String propertyName;
Class classFromPropertyType;
Constructor constructor;
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
writeMethod = propertyDescriptor.getWriteMethod();
propertyName = propertyDescriptor.getName();
classFromPropertyType = propertyDescriptor.getPropertyType();
if (map.containsKey(propertyName)) {
constructor = classFromPropertyType.getConstructor(String.class);
writeMethod.invoke(liuRui, constructor.newInstance(map.get(propertyName)));
}
}
return liuRui;
}
}