• Spring BeanUtils copyProperties list 带来的问题


    一、示例:把人类复制到动物类

    1、人类,关键点在于 腿 这个列表

    1. @Data
    2. public class Human {
    3. /**
    4. * 姓名
    5. */
    6. private String name;
    7. /**
    8. * 人的腿
    9. */
    10. private List legs;
    11. }

    2、腿类,有两个属性,长度和数量

    1. @Data
    2. public class Leg {
    3. /**
    4. * 长度
    5. */
    6. private Integer length;
    7. /**
    8. * 数量
    9. */
    10. private Integer num;
    11. }

    3、动物类,有个爪子的列表,属性名叫legs,为了与人类保持一致,这样才能拷贝

    1. @Data
    2. public class Animal {
    3. /**
    4. * 姓名
    5. */
    6. private String name;
    7. /**
    8. * 动物的腿(爪子)
    9. */
    10. private List legs;
    11. }

    4、爪子类,注意与腿类的区别,它没有 数量的属性

    1. @Data
    2. public class Claw {
    3. /**
    4. * 长度
    5. */
    6. private Integer length;
    7. }

    5、测试类:把人这个对象复制到动物对象

    1. public class Test {
    2. public static void main(String[] args) {
    3. //从人复制到动物
    4. Human human = new Human();
    5. human.setName("张三");
    6. List legs = new ArrayList<>();
    7. Leg leg = new Leg();
    8. leg.setLength(1);
    9. leg.setNum(2);
    10. legs.add(leg);
    11. human.setLegs(legs);
    12. Animal animal = new Animal();
    13. BeanUtils.copyProperties(human, animal);
    14. System.out.println(JSON.toJSONString(animal));
    15. }
    16. }

    6、测试结果:

    {"legs":[{"length":1,"num":2}],"name":"张三"}

    7、大家看出来什么了没有?

    居然JSON String里面输出了num的属性,而在Claw类里面根本就没有该属性,这是为什么?

    8、我们稍微修改一下测试类,在代码的最后增加一行代码:

    1. public class Test {
    2. public static void main(String[] args) {
    3. //从人复制到动物
    4. Human human = new Human();
    5. human.setName("张三");
    6. List legs = new ArrayList<>();
    7. Leg leg = new Leg();
    8. leg.setLength(1);
    9. leg.setNum(2);
    10. legs.add(leg);
    11. human.setLegs(legs);
    12. Animal animal = new Animal();
    13. BeanUtils.copyProperties(human, animal);
    14. System.out.println(JSON.toJSONString(animal));
    15. Claw claw = animal.getLegs().get(0);
    16. }
    17. }

    9、测试结果:

    1. {"legs":[{"length":1,"num":2}],"name":"张三"}
    2. Exception in thread "main" java.lang.ClassCastException: com.dd.Leg cannot be cast to com.dd.Claw
    3. at com.dd.Test.main(Test.java:26)

    10、原因分析:

    在BeanUtils.copyProperties的时候,执行的是浅复制,在对list进行复制的时候,因为泛型擦除,直接把List复制到List,实际上Animal里面的List存储的是Leg,而不是Claw。

    所以我们在使用BeanUtils.copyProperties需要注意对于集合类的处理。

  • 相关阅读:
    JAVA大型OA协同办公系统源码【源码免费分享】
    Linux 进程管理
    java基于ssm的共享快递盒管理系统
    ucOS-II在STM32F1移植
    GenICam GenTL 标准 ver1.5(2)
    在线流程图和思维导图开发技术详解(四)
    哈希(Hash)
    P2P 技术:点对点网络的兴起
    知识星球2023年10月PHP函数小挑战
    机械搬运手结构设计
  • 原文地址:https://blog.csdn.net/duzm200542901104/article/details/126123739