如实体类A为bird类,实体B为dog类,bird类和dog类都有animalId(主键)、leg、eye属性,但是bird类比dog类多一个wing属性。
现在需要把一个bird类的对象值赋值给dog类,怎么快速做到呢?
可以借助org.springframework.beans的工具类BeanUtils中的copyProperties的静态方法,
BeanUtils.copyProperties(Object source,Object target)
source和target为对象,方法是将source的属性拷贝到target对应属性中。
注:
- target的属性source中必须有,但是target可有source没有的属性
- source和target需要赋值的属性,属性名必须完全相同
- 需要赋值的属性,在实体类中需要有getter,setter方法
示例,将bird对象赋值到dog对象中。
public class Dog{
private int animalId;
private String leg;
private String eye;
public Dog(int animalId,String leg,String eye){
this.animalId = animalId;
this.leg = leg;
this.eye = eye;
}
public int getAnimalId() {
return animalId;
}
public void setAnimalId(int animalId) {
this.animalId = animalId;
}
public String getLeg() {
return leg;
}
public void setLeg(String leg) {
this.leg = leg;
}
public String getEye() {
return eye;
}
public void setEye(String eye) {
this.eye = eye;
}
}
public class Bird{
private int animalId;
private String leg;
private String eye;
private String wing;
public Bird(int animalId,String leg,String eye,String wing){
this.animalId = animalId;
this.leg = leg;
this.eye = eye;
this.wing = wing;
}
//省略getter和setter方法的代码
}
Dog dog = new Dog(1,"四条腿","大眼睛");
Bird bird = new Bird(2,"两条腿","小眼睛","两只翅膀");
BeanUtils.copyProperties(bird,dog);//将bird对象aniamlId,leg,eye属性赋值给dog对象,bird多的wing属性不会赋值给dog。