一、认识
首先说一说BeanUtils简介。
百度告诉我:BeanUtils提供对Java反射和自省API的包装。其主要目的是利用反射机制对JavaBean的属性进行处理。那么为什么要使用它呢?简单来说就是当我使用BeanUtils的时候,可以避免大量的get/set代码,使我的代码更加简洁。
二、举例
PeopleForm peopleForm=(PeopleForm)form; //得到PeopleForm
People people=new People(); //构造People对象
//赋值
people.setName(peopleForm.getName());
people.setPhone(peopleForm.getPhone());
people.setAddress(peopleForm.getAddress());
people.setAge(peopleForm.getAge());
people.setRank(peopleForm.getRank());
当我有了BeanUtils.copyProperties()方法后:
PeopleForm peopleForm=(PeopleForm)form; //得到PeopleForm
People people=new People(); //构造People对象
//赋值
BeanUtils.copyProperties(peopleForm,people);
代码简洁了。
总结用法
BeanUtils.copyProperties()这个方法,在不同包下,传递参数赋值是相反的
包一: org.springframework.beans.BeanUtils,(上面的举例是在这个包里)
包二:org.apache.commons.beanutils.BeanUtils,
例如:a,b为对象,**BeanUtils.copyProperties(a, b)**的两个包对应的用法:
BeanUtils是org.springframework.beans.BeanUtils ===> a拷贝到b
BeanUtils是org.apache.commons.beanutils.BeanUtils ===> b拷贝到a
我的项目里是用的org.springframework.beans.BeanUtils,总算排查出来了。