Java使用序列化實現深克隆
阿新 • • 發佈:2020-12-24
技術標籤:Java中級
好記性不如爛筆頭,複習一下深克隆
實際使用時由於序列化的方式實現深度克隆效能較差,還是推薦使用Cloneable介面的方式重寫clone方法,但是注意該方法需要注意克隆物件的物件(多層)
話不多說,下面講一下深度克隆,深克隆實現相對簡單一點,只需要被克隆的物件實現Serializable介面,克隆的過程相對比較通用
被克隆物件:
import java.io.Serializable; public class SerialCar implements Serializable { private static final long serialVersionUID = -7308342867043888945L; private String carType; private String carName; public SerialCar() { } public SerialCar(String carType, String carName) { this.carType = carType; this.carName = carName; } public String getCarType() { return carType; } public void setCarType(String carType) { this.carType = carType; } public String getCarName() { return carName; } public void setCarName(String carName) { this.carName = carName; } @Override public String toString() { return "SerialCar{" + "carType='" + carType + '\'' + ", carName='" + carName + '\'' + '}'; } }
import java.io.Serializable; public class SerialUser implements Serializable { private static final long serialVersionUID = -2167957013938386204L; private String username; private SerialCar serialCar; public SerialUser() { } public SerialUser(String username, SerialCar serialCar) { this.username = username; this.serialCar = serialCar; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public SerialCar getSerialCar() { return serialCar; } public void setSerialCar(SerialCar serialCar) { this.serialCar = serialCar; } @Override public String toString() { return "SerialUser{" + "username='" + username + '\'' + ", serialCar=" + serialCar + '}'; } }
測試程式碼:
import java.io.*; public class TestDeepClone { public static void main(String[] args) throws IOException, ClassNotFoundException { SerialUser serialUser = new SerialUser("李四", new SerialCar("賓士", "250")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(serialUser); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); SerialUser cloneUser = (SerialUser)ois.readObject(); SerialCar cloneCar = cloneUser.getSerialCar(); cloneCar.setCarType("奧迪"); cloneCar.setCarName("A8"); System.out.println(serialUser); System.out.println(cloneUser); } }
測試結果: