在Java中如果要将一个对象的值赋给另外一个对象,那么使用BeanUtils.copyProperties方法是极其方便的。下面介绍简单使用方法。
例:有两个类Emp和EmpVo,要将Emp对象的值赋给EmpVo对象(注意:只能对两个对象的相同属性进行赋值,如果某个属性只有EmpVo类包含,赋值后EmpVo该属性的值依然为空)。
Emp类:
public class Emp {
private String id;
private String empname;
private BigDecimal salary;
private Date birth;
private Integer age;
private Integer depID;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname == null ? null : empname.trim();
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getDepID() {
return depID;
}
public void setDepID(Integer depID) {
this.depID = depID;
}
}
EmpVo类:
public class EmpVo {
private String id;
private String empname;
private BigDecimal salary;
private Date birth;
private Integer age;
private Integer depID;
private String depName;
public EmpVo() {
}
public EmpVo(String id, String empname, BigDecimal salary, Date birth, Integer age, Integer depID, String depName) {
this.id = id;
this.empname = empname;
this.salary = salary;
this.birth = birth;
this.age = age;
this.depID = depID;
this.depName = depName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getDepID() {
return depID;
}
public void setDepID(Integer depID) {
this.depID = depID;
}
public String getDepName() {
return depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
}
测试类:
public class Demo
{
public void test(){
Emp emp=new Employee();
EmpVo empVo=new EmpVo ();
BeanUtil.copyProperties(emp, empVo);
}
}
这样就可以将Emp对象的值赋给EmpVo了。
理想和现实总是有差距的,幸好有差距,不然,谁还稀罕理想。