import java.util.Date;
public class People {
private String name;
private int age;
private Date birth;
public People(String name, int age, Date birth) {
super();
this.name = name;
this.age = age;
this.birth = birth;
}
public People() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "People [name=" + name + ", age=" + age + ", birth=" + birth + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
}
测试(所有测试只与源javabean属性值有关,与目标javabean属性值无关)
当源javabean属性均有值时的目标javabean属性复制情况
@Test
public void springBeanUtilsTest(){
People oldPeople = new People("oldName",100,new Date());
People newPeople = new People();
//BeanUtils.copyProperties(Object source,Object target);
BeanUtils.copyProperties(oldPeople, newPeople);
System.out.println(oldPeople);
System.out.println(newPeople);
}
输出结果如下
People [name=oldName, age=100, birth=Wed Jul 19 18:46:13 CST 2017]
People [name=oldName, age=100, birth=Wed Jul 19 18:46:13 CST 2017]
当源javabean非Date类型的属性值为null时目标javabean属性的复制情况
@Test
public void springBeanUtilsTest(){
People oldPeople = new People(null,100,new Date());
People newPeople = new People("newName",20,null);
//BeanUtils.copyProperties(Object source,Object target);
BeanUtils.copyProperties(oldPeople, newPeople);
System.out.println(oldPeople);
System.out.println(newPeople);
}
输出结果如下
注意:目标javabean中的非null属性值被覆盖为null了
People [name=null, age=100, birth=Wed Jul 19 19:04:48 CST 2017]
People [name=null, age=100, birth=Wed Jul 19 19:04:48 CST 2017]
当源javabean中Date类型的属性值为null时目标javabean中属性值的复制情况
@Test
public void springBeanUtilsTest(){
People oldPeople = new People("oldName",100,null);
People newPeople = new People("newName",20,new Date());
//BeanUtils.copyProperties(Object source,Object target);
BeanUtils.copyProperties(oldPeople, newPeople);
System.out.println(oldPeople);
System.out.println(newPeople);
}
输出结果如下
People [name=oldName, age=100, birth=null]
People [name=oldName, age=100, birth=null]