Spring中BeanUtils.copyProperties的坑及解决

  import cn.hutool.core.bean.BeanUtil;

  import cn.hutool.core.collection.CollUtil;

  import cn.hutool.core.date.DateUtil;

  import java.util.*;

  public class Example {

  public static void main(String[] args) {

  // 创建一个子类对象

  Child source = new Child();

  source.setPublicField("public field");

  source.setProtectedField("protected field");

  source.setPrivateField("private field");

  source.setDateField(DateUtil.parse("2023-05-22"));

  source.setStringList(CollUtil.newArrayList("a", "b", "c"));

  source.setStringMap(new HashMap() {{

  put("key1", "value1");

  put("key2", "value2");

  }});

  // 创建一个父类对象

  Parent target = new Parent();

  // 将子类对象的属性拷贝到父类对象中

  BeanUtil.copyProperties(source, target);

  // 输出父类对象中的属性

  System.out.println("publicField: " + target.getPublicField());

  System.out.println("protectedField: " + target.getProtectedField());

  System.println("privateField: " + target.getPrivateField());

  System.out.println("dateField: " + target.getDateField());

  System.out.println("stringList: " + target.getStringList());

  System.out.println("stringMap: " + target.getStringMap());

  }

  }

  // 父类

  class Parent {

  private String privateField;

  private Date dateField;

  private List stringList;

  private Map stringMap;

  public String getPrivateField() {

  return privateField;

  }

  public void setPrivateField(String privateField) {

  this.privateField = privateField;

  }

  public Date getDateField() {

  return dateField;

  }

  public void setDateField(Date dateField) {

  this.dateField = dateField;

  }

  public List getStringList() {

  return stringList;

  }

  public void setStringList(List stringList) {

  this.stringList = stringList;

  }

  public Map getStringMap() {

  return stringMap;

  }

  public void setStringMap(Map stringMap) {

  this.stringMap = stringMap;

  }

  }

  // 子类

  class Child extends Parent {

  public String publicField;

  protected String protectedField;

  public String getPublicField() {

  return publicField;

  }

  public void setPublicField(String publicField) {

  this.publicfield = publicField;

  }

  public String getProtectedField() {

  return protectedField;

  }

  public void setProtectedField(String protectedField) {

  this.protectedField = protectedField;

  }

  private String privateField;

  public String getPrivateField() {

  return privateField;

  }

  public void setPrivateField(String privateField) {

  this.privateField = privateField;

  }

  }