一、参考文献
1.1 https://blog.csdn.net/forwujinwei/article/details/79915872
1.2
二、深度拷贝实现方式1
2.1 通过序列化实现深拷贝
2.1.1 注意事项
2.1.1.1 用此方法写深度拷贝的类需要实现Serializable, Cloneable 接口
2.1.1.2 字段引用的对象要实现Serializable
public class Cat implements Serializable, Cloneable { private String name; private String color; private Dog friend; public Cat deepClone() throws IOException, ClassNotFoundException { //将对象写入流中 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(this); //从流中取出 ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); return (Cat) objectInputStream.readObject(); }}
2.2 通过Jackson实现
2.2.1 性能不清楚,但是这个方式比较方便
ObjectMapper mapper = new ObjectMapper(); String catString = mapper.writeValueAsString(cat); Cat catCopy = mapper.readValue(catString, Cat.class);
工具类
public staticT deepClone(T obj) { try { String s = mapper.writeValueAsString(obj); T t = mapper.readValue(s, (Class ) obj.getClass()); return t; } catch (Exception e) { log.error("deepClone error{}", e); } return null; }//使用Cat catCopy = deepClone(cat);
2.3 commons-beanutils工具类(推荐此方法)
commons-beanutils commons-beanutils 1.9.3