JoeyWong

场景:需要对某个集合中的所有元素拷贝到另一个集合中,想着BeanUtils.copyProperties()可以深拷贝对象,误以为也可以拷贝集合,于是乎写下了如下代码

  List<CostRule> meetCostRuleList = Lists.newArrayList();
  BeanUtils.copyProperties(partItemRuleList, meetCostRuleList);

以上的操作结果不会报错,但是 meetCostRuleList  集合仍是一个空集合;由于业务复杂,该块没有被测试到,上线初了问题,后来更改为

 List<CostRule> meetCostRuleList = Lists.newArrayList();
 partItemRuleList.forEach(costRule -> meetCostRuleList.add(costRule));

谨记:BeanUtils.copyProperties只对bean属性进行复制,这里的复制属于浅复制。且不能复制集合和数组。BeanUtils.copyProperties利用反射,直接将对象的引用set进去,并不是深拷贝。

分类:

技术点:

相关文章:

  • 2021-03-08
  • 2021-12-12
  • 2021-09-18
  • 2021-12-02
  • 2021-08-05
  • 2021-09-18
  • 2022-01-02
  • 2021-09-28
猜你喜欢
  • 2021-11-05
  • 2021-06-09
  • 2021-10-27
  • 2021-06-08
  • 2021-07-11
  • 2021-11-22
  • 2021-09-08
相关资源
相似解决方案