HashMap转JavaBean,深入剖析

//把Map转化为JavaBean

public static <T> T map2bean(Map<String,Object> map,Class<T> clz) throws Exception{

	T obj = clz.newInstance();

	//从Map中获取和属性名称一样的值,把值设置给对象(setter方法)

	BeanInfo b = Introspector.getBeanInfo(clz,Object.class);

	PropertyDescriptor[] pds = b.getPropertyDescriptors();

	for (PropertyDescriptor pd : pds) {

		//得到属性的setter方法

		Method setter = pd.getWriteMethod();

		//得到key名字和属性名字相同的value设置给属性

		setter.invoke(obj, map.get(pd.getName()));

	}

	return obj;

}





public static <T> T populate(Map<String, Object> map, Class<T> clz) throws Exception {

	T obj = clz.newInstance();

	//拿到  BeanInfo

	BeanInfo beanInfo = Introspector.getBeanInfo(clz);

	//通过 beaninfo 获取所有的描述器

	PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

	for (PropertyDescriptor pd : pds) {

		//获取属性的名字

		String name = pd.getName();

		//判断是否有这个属性

		if (map.containsKey(name)){

			//获取属性的  写的方法

			Method wMethod = pd.getWriteMethod();

			if (pd.getPropertyType() == int.class){

				wMethod.invoke(obj,Integer.valueOf(map.get(name).toString()));

			}else if (pd.getPropertyType() == double.class){

				wMethod.invoke(obj,Double.valueOf(map.get(name).toString()));

			}else {

				wMethod.invoke(obj,map.get(name));

			}

		}

	}

	return obj;

}

2、方式一升级款

//map转换成Bean,只要Map键和JavaBean属性名一致即可,解决mapToBean因为单个首字母大写,映射找不到属性的问题

public static <T, V> T mapToBeanByField(Map<String,V> map,Class<T> clz) throws Exception{

	T obj = clz.newInstance();

	Field field = null;

	for(String key : map.keySet()) {

		field = obj.getClass().getDeclaredField(key);

		field.setAccessible(true);

		field.set(obj, map.get(key));

	}

	return obj;

}

3、方式二

经验分享 程序员 微信小程序 职场和发展