一文搞懂Java克隆及深拷贝与浅拷贝的区别

  import java.io.*;

  class Address implements Serializable {

  private String city;

  private String street;

  public Address(String city, String street) {

  this.city = city;

  this.street = street;

  }

  public void setCity(String city) {

  this.city = city;

  }

  public void setStreet(String street) {

  this.street = street;

  }

  public String getCity() {

  return city;

  }

  public String getStreet() {

  return street;

  }

  }

  class Person implements Serializable {

  private String name;

  private int age;

  private Address address;

  public Person(String name, int age, Address address) {

  this.name = name;

  this.age = age;

  this.address = address;

  }

  public void setName(String name) {

  this.name = name;

  }

  public void setAge(int age) {

  this.age = age;

  }

  public void setAddress(Address address) {

  this.address = address;

  }

  public String getName() {

  return name;

  }

  public int getAge() {

  return age;

  }

  public Address getAddress() {

  return address;

  }

  }

  public class Main {

  public static void main(String[] args) {

  Address address = new Address("City", "Street");

  Person person1 = new Person("Alice", 25, address);

  // 深拷贝

  Person person2 = deepCopy(person1);

  System.out.println(person1.getName() + " " + person1.getAge() + " " + person1.getAddress().getCity()); // Alice 25 City

  System.out.println(person2.getName() + " " + person2.getAge() + " " + person2.getAddress().getCity()); // Alice 25 City

  person2.setName("Bob");

  person2.setAge(30);

  person2.getAddress().setCity("New City");

  System.out.println(person1.getName() + " " + person1.getAge() + " " + person1.getAddress().getCity()); // Alice 25 City

  System.out.println(person2.getName() + " " + person2.getAge() + " " + person2.getAddress().getCity()); // Bob 30 New City

  }

  public static T deepCopy(T object) {

  try {

  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);

  objectOutputStream.writeObject(object);

  objectOutputStream.flush();

  ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

  ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);

  return (T) objectInputStream.readObject();

  } catch (IOException | ClassNotFoundException e) {

  e.printStackTrace();

  return null;

  }

  }

  }