BeanUtils.copyProperties的使用(深拷贝,浅拷贝)

BeanUtils.copyProperties的使用(深拷贝,浅拷贝)这里说的是 spring 的 BeanUtils copyProperti 场景开发中经常遇到 把父类的属性拷贝到子类中 通常有 2 种方法 1 一个一个 set2 用 BeanUtils copyProperti 很显然 BeanUtils 更加方便 也美观很多 那么任何情况都能使用 BeanUtils 么 当然不是 要先了解他 是深拷贝 还是浅拷贝 是浅拷贝 浅拷贝 只是调用子对象的 set

这里说的是spring的BeanUtils.copyProperties。

场景

BeanUtils是深拷贝,还是浅拷贝?

什么情况适合用BeanUtils

如果都是单一的属性,那么不涉及到深拷贝的问题,适合用BeanUtils。

有子对象就一定不能用BeanUtils么

代码例子

Father类:

@Data public class Father { 
     private String face; // 长相 private String height; // 身高 private Life life; // 生命 } 

Life 类:

@Data public class Life { 
     private String status; } 

Son类和main方法:

@Data public class Son extends Father{ 
     private Life life; public static void main(String[] args) { 
     Father cuishan = new Father(); cuishan.setFace("handsome"); cuishan.setHeight("180"); Life cuishanLife = new Life(); cuishanLife.setStatus("alive"); cuishan.setLife(cuishanLife); Son wuji=new Son(); BeanUtils.copyProperties(cuishan,wuji); // Life wujiLife = wuji.getLife(); // wujiLife.setStatus("alive"); // wuji.setLife(wujiLife); // cuishanLife.setStatus("dead"); // 翠山后来自刎了 System.out.println(JSON.toJSONString(cuishan)); System.out.println(JSON.toJSONString(wuji)); } } 
// Life wujiLife = wuji.getLife(); // wujiLife.setStatus("alive"); // wuji.setLife(wujiLife); // cuishanLife.setStatus("dead"); // 翠山后来自刎了 

case2: 翠山自刎,无忌设置或者,翠山也活了

// cuishanLife.setStatus("dead"); // 翠山后来自刎了 // Life wujiLife = wuji.getLife(); // wujiLife.setStatus("alive"); // wuji.setLife(wujiLife); 

case3: 翠山和无忌互不影响

 cuishanLife.setStatus("dead"); // 翠山自刎了 该行放在上下均可 // 无忌用个新对象 不受翠山影响了 Life wujiLife = new Life(); wujiLife.setStatus("alive"); wuji.setLife(wujiLife); 

dest ,src 还是 src,dest

区别如下:

spring的BeanUtils commons的BeanUtils
方法 copyProperty和copyProperties copyProperties
参数 src ,dest dest,src

这2个用哪个都行,但是要注意区别。 因为他们2个的src和dest是正好相反的,要特别留意。


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/207988.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月19日 下午12:37
下一篇 2026年3月19日 下午12:38


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号