使用org.springframework.beans.BeanUtils..copyProperties()方法进行copy两个类的属性。
注意:
1.源类Sourse中的属性需有get方法;
2.目标类Target中的属性需有set方法;
3.复制期间只会复制名字相同的属性值;
Sourse:
package com.yoyo.yotils.yoyo.copyProperties;
/**
*
* @author yoyo
* @version $Id: Sourse.java, v 0.1 2019年06月17日 12:13 yoyo Exp $
*/
public class Sourse {
private String name;
private String sex;
private int age;
public Sourse(String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
/**
* Getter method for property <tt>name</tt>.
*
* @return property value of name
*/
public String getName() {
return name;
}
/**
* Getter method for property <tt>sex</tt>.
*
* @return property value of sex
*/
public String getSex() {
return sex;
}
/**
* Getter method for property <tt>age</tt>.
*
* @return property value of age
*/
public int getAge() {
return age;
}
}
Target类:
package com.yoyo.yotils.yoyo.copyProperties;
import org.springframework.beans.BeanUtils;
/**
*
* @author yoyo
* @version $Id: Target.java, v 0.1 2019年06月17日 12:14 yoyo Exp $
*/
public class Target {
private String name;
private String sex;
private int age;
private String address;
Target copyFromSourse(Sourse sourse){
BeanUtils.copyProperties(sourse, this);
return this;
}
@Override
public String toString() {
return "Target{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", address=" + address +
'}';
}
/**
* Setter method for property <tt>name</tt>.
*
* @param name value to be assigned to property name
*/
public void setName(String name) {
this.name = name;
}
/**
* Setter method for property <tt>sex</tt>.
*
* @param sex value to be assigned to property sex
*/
public void setSex(String sex) {
this.sex = sex;
}
/**
* Setter method for property <tt>age</tt>.
*
* @param age value to be assigned to property age
*/
public void setAge(int age) {
this.age = age;
}
/**
* Setter method for property <tt>address</tt>.
*
* @param address value to be assigned to property address
*/
public void setAddress(String address) {
this.address = address;
}
}
测试类:
package com.yoyo.yotils.yoyo.copyProperties;
/**
*
* @author yoyo
* @version $Id: Test.java, v 0.1 2019年06月17日 12:15 yoyo Exp $
*/
public class Test {
public static void main(String[] args) {
Sourse sourse = new Sourse("tom", "male", 13);
Target target = new Target().copyFromSourse(sourse);
System.out.println(target.toString());
}
}
结果: