java map转bean_java BeanUtils实现Map和Bean的相互转换

1、bean 转换成 map

Person person1=new Person();

person1.setName("name1");

person1.setSex("sex1");

Map map=null;

try {

map = BeanUtils.describe(person1);

2、map 转换成 bean

BeanUtils位于org.apache.commons.beanutils.BeanUtils下面,其方法populate的作用解释如下:

完整方法:

BeanUtils.populate( Object bean, Map properties ),

这个方法会遍历map中的key,如果bean中有这个属性,就把这个key对应的value值赋给bean的属性。/**

*

*

* Map转换层Bean,使用泛型免去了类型转换的麻烦。

* @param 

* @param map

* @param class1

* @return

*/

public static  T map2Bean(Map map, Class class1) {

T bean = null;

try {

bean = class1.newInstance();

BeanUtils.populate(bean, map);

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

}

return bean;

}

你可能感兴趣的:(java,map转bean)