1. 复现前准备三个类,Student、Source、Target。Source和Target里面包含一个相同的非基本类型的字段(如下面示例中的stu字段)
public class Student {
    private String name;

    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


public class Source {
    private List<Student> stu;

    public List<Student> getStu() {
        return stu;
    }

    public void setStu(List<Student> stu) {
        this.stu = stu;
    }

}


public class Target {
    private List<String> stu;

    public List<String> getStu() {
        return stu;
    }

    public void setStu(List<String> stu) {
        this.stu = stu;
    }
}

  1. 复现
public static void main(String[] args) {
        Source source = new Source();
        source.setStu(Arrays.asList(new Student("John"), new Student("Jane")));

        Target target = new Target();
        BeanUtil.copyProperties(source, target);

        // 目前target里面的stu字段类型本身是String,但是copy的时候把source中stu的引用放到了target.stu里面
        System.out.println(target.getStu().get(0));  // 会报错: Student cannot be cast to java.lang.String
        
    }

  1. 总结
    待补充

  2. 解决办法

  • 手动get、set
  • 使用其他第三方工具