暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

BeanUtils.copyProperties的坑

yuerer 2024-03-26
168

1.性能比较低,BeanUtils用反射,是在运行阶段相对来说比get、set方法慢

2.浅拷贝,如果属性是对象,不是基本类型,只复制对象及其引用,而不复制引用指向的对象本身

3.Boolean类型数据+is属性开头,赋值失败


1.性能比较低

---BeanUtils.copyProperties的效率




---get 和 set的效率



2.浅拷贝

public class Address {
    private String city;
    //getter 和 setter 方法省略
}
 
public class Person {
    private String name;
    private Address address;
    //getter 和 setter 方法省略
}
 
 Person sourcePerson = new Person();
 sourcePerson.setName("John");
 Address address = new Address();
 address.setCity("New York");
 sourcePerson.setAddress(address);
 
 Person targetPerson = new Person();
 BeanUtils.copyProperties(sourcePerson, targetPerson);
 
 sourcePerson.getAddress().setCity("London");
 
 System.out.println(targetPerson.getAddress().getCity());  // 输出为 "London"
复制


3.Boolean类型数据+is属性开头,赋值失败

@Data
public class SourceBean {
    private boolean isTianLuo;
}
 
@Data
public class TargetBean {
    private Boolean isTianLuo;
}
复制


SourceBean source = new SourceBean();
source.setTianLuo(true);
 
TargetBean target = new TargetBean();
BeanUtils.copyProperties(source, target);
System.out.println(target.getIsTianLuo()); // 输出为 null
复制

因为当属性类型为boolean时,属性名以is开头,属性名会去掉前面的is,因此源对象和目标对象属性对不上

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论