导入不同的包结果完全不一样
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); } }