1.populate方法使用:
首先,它是在org.apache.commons.beanutils.BeanUtils包中的一个方法。
方法的作用:用来将一些 key-value 的值(例如 hashmap)映射到 bean 中的属性。
servlet中有这样的使用:
先定义form表单内容的Info对象(当然你要先写一个bean,这个bean中包含form表单中各个对象的属性)
InsuranceInfo info = new InsuranceInfo(); (这是一个javabean)
BeanUtilities.populateBean(info, request);
——> populateBean(info, request.getParameterMap());(先将request内容转为Map类型)
——>BeanUtils.populate(info, propertyMap);(调用包中方法映射)
映射的过程就是将页面中的内容先用request获得,然后再将之转换为Map(这里用request.getParameterMap())
最后使用BeanUtils.populate(info,map)方法将页面各个属性映射到bean中。之后我们就可以这样使用bean.getXxxx()来取值了。
实例:
Map<String, String> paramMap = request.getParameterMap();
logger.info("微信登录/绑定请求参数:{}", paramMap);
WxBindingForm wxform = new WxBindingForm();
BeanUtils.populate(wxform, paramMap);//WxBindingForm 获得map的值
//可以通过wxform.getxxx()获取bean中的属性值了
2.setProperty
Person p = new Person();
BeanUtils.setProperty(p, "name", "victor");
3.copyProperties()
2、 BeanUtils.copyProperties(obj1,obj2); 经常闹混不知道是谁给谁赋值,无意中先到"后付前"这个词来帮助自己记忆这个功能。即将obj2的值赋值给obj1。
3、 如果2中实例obj2为空对象,即值new了他的实例并没有赋值的话obj1对应的属性值也会被设置为空置。
4、BeanUtils与PropertyUtils对比(这里对比copyProperties方法)
PropertyUtils的copyProperties()方法几乎与BeanUtils.copyProperties()相同,主要的区别在于后者提供类型转换功能,即发现两个JavaBean的同名属性为不同类型时,在支持的数据类型范围内进行转换,BeanUtils 不支持这个功能,但是BeanUtils速度会更快一些。