Java Object Clone
Posted stono
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Object Clone相关的知识,希望对你有一定的参考价值。
Java Object Clone
User user = new User(); user.setName("tom"); User user1 = new User(); user1.setName("jerry"); List<User> list = new ArrayList<>(); list.add(user1); user.setChildren(list); user.setUser(user1); System.out.println(user); User2 user2 = new User2(); BeanUtils.copyProperties(user2,user); System.out.println(user2); List<User2> children = user2.getChildren(); // 此处会出现错误 for (User2 user21 :children ) { System.out.println(user21); } User user3 = (User) BeanUtils.cloneBean(user); System.out.println(user3);
user:
package com.test; import java.util.List; public class User { private String name; private List<User> children; private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "User{" + "name=‘" + name + ‘‘‘ + ", children=" + children + ", user=" + user + ‘}‘; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<User> getChildren() { return children; } public void setChildren(List<User> children) { this.children = children; } }
user2:
package com.test; import java.util.List; public class User2 { private String name; private List<User2> children; private User2 user2; public User2 getUser2() { return user2; } public void setUser2(User2 user2) { this.user2 = user2; } @Override public String toString() { return "User2{" + "name=‘" + name + ‘‘‘ + ", children=" + children + ", user2=" + user2 + ‘}‘; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<User2> getChildren() { return children; } public void setChildren(List<User2> children) { this.children = children; } }
注意和spring beanutils的区别:
https://blog.csdn.net/langqiao123/article/details/72961383/
传说spring Beanutils的性能要更好一些;
以上是关于Java Object Clone的主要内容,如果未能解决你的问题,请参考以下文章
阿里公约推荐慎用 Object 的 clone 方法来拷贝对象。
为啥 Object.clone() 在 Java 中是原生的?
JAVA克隆对象报错:The method clone() from the type Object is not visible