導入不同的包結果完全不一樣
Spring 的 BeanUtils (推薦使用)
前一個內容 復制到 后一個
Apache 的 BeanUtils (性能差 不推薦使用)
后一個內容 復制到 前一個

public class Student { /** 學號 */ private long id; private String name; private int age; /** 年級 */ private int grade; /** 專業 */ private String major; /** 學校 */ private String school; public long getId() { return id; } public void setId(long id) { this.id = id; } 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 int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public Student(long id, String name, int age, int grade, String major, String school) { super(); this.id = id; this.name = name; this.age = age; this.grade = grade; this.major = major; this.school = school; } @Override public String toString() { return String.format("Student [id=%s, name=%s, age=%s, grade=%s, major=%s, school=%s]", id, name, age, grade, major, school); } }
import java.lang.reflect.InvocationTargetException; import org.springframework.beans.BeanUtils; //import org.apache.commons.beanutils.BeanUtils; public class Test { public static void main(String[] args) throws IllegalAccessException, InvocationTargetException { Student studentA = new Student(200123, "蘇明", 20, 1, "土木工程", null); Student studentB = new Student(200789, "張阿凡", 20, 3, "計算機工程", "蘇州工業大學"); //后一個內容 復制到 前一個 //用studentB 替換 studentA的字段內容 BeanUtils.copyProperties(studentA, studentB); //結果都是后一個內容 System.out.println(studentA); System.out.println(studentB); } }