clone

使用Object.clone() 创建出一个和原对象内容一样,地址不一样的对象

浅拷贝

实现Cloneable接口,重写clone方法,调用父类的clone方法,将返回值类型强转成本类类型

  1. @Data
  2. public class Person implements Cloneable{
  3. private String name;
  4. private int age;
  5. private Children child;
  6. @Override
  7. public String toString() {
  8. return "Person{" +
  9. "name='" + name + '\'' +
  10. ", age=" + age +
  11. '}';
  12. }
  13. @Override
  14. public Person clone() throws CloneNotSupportedException {
  15. return (Person) super.clone();
  16. }
  17. }

浅拷贝的缺点:
拷贝出来的对象的引用类型的成员变量 child 是同一个引用

clone的深拷贝实现:

  1. @Override
  2. public Person clone() throws CloneNotSupportedException {
  3. Person clone = (Person) super.clone();
  4. clone.setChild(child.clone());
  5. return clone;
  6. }

IO实现深拷贝

  1. // Person需要实现Serializable
  2. @Override
  3. public Person clone() {
  4. try {
  5. //1. 创建ByteArrayOutputStream,将数据可以转换成字节
  6. ByteArrayOutputStream bout = new ByteArrayOutputStream();
  7. //2. 创建ObjectOutputStream,关联ByteArrayOutputStream
  8. ObjectOutputStream out = new ObjectOutputStream(bout);
  9. //3. 使用ObjectOutputStream的writeObject,读取要复制的对象
  10. out.writeObject(this);
  11. //4. 使用ByteArrayInputStream读取ByteArrayOutputStream的转换的对象字节数据
  12. ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
  13. //5. 创建ObjectInputStream读取对象字节数据,创建新的对象
  14. ObjectInputStream in = new ObjectInputStream(bin);
  15. Person clone = (Person) in.readObject();
  16. return clone;
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. return null;
  20. }
  21. }