One. Serialization:
The process of writing an object into a stream is serialized, and the process of reading the object from the stream is called deserialization. In Java, it is often possible to implement a deep-clone object by enabling the object to implement the Serializable interface, then writing the object into a stream and then reading it from the stream to reconstruct the object.
Two. Serialization implementation:
<strong><span style= "FONT-SIZE:14PX;" >public class Main{public static void Main (string[] args) throws Exception{teacher3 t = new Teacher3 (); T.setage (+); T.s Etname ("Teacher Zhang"); Student3 S1 = new Student3 () s1.setage; S1.setname ("Zhangsan"); S1.setteacher (t); Student3 s2 = (Student3) s1.deepcopy (); System.out.println (S2.getage ()); System.out.println (S2.getname ()); System.out.println ("-----------------------"); System.out.println (S2.getteacher (). Getage ()); System.out.println (S2.getteacher (). GetName ()); S2.getteacher (). Setage () S2.getteacher () setName ("Teacher Li"); System.out.println (S1.getteacher (). Getage ()); System.out.println (S1.getteacher (). GetName ());}} Class Teacher3 implements Serializable{private int age;private String name;public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}} Class Student3 implements Serializable{private int age;private String name;private TEACHer3 teacher;public int Getage () {return age;} public void Setage (int.) {this.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public Teacher3 Getteacher () {return teacher;} public void Setteacher (Teacher3 teacher) {this.teacher = teacher;} Public Object deepcopy () throws Exception{bytearrayoutputstream bos = new Bytearrayoutputstream (); ObjectOutputStream Oos = new ObjectOutputStream (BOS); Oos.writeobject (this); Bytearrayinputstream bis = new Bytearrayinputstream (Bos.tobytearray ()); ObjectInputStream ois = new ObjectInputStream ( bis); return Ois.readobject ();}} </span></strong>
Print:
20
Zhangsan
-----------------------
40
Teacher Zhang
40
Teacher Zhang
Three. Serialversionuid Meaning:
Serialversionuid is intended to make the category serializable backwards compatible. For example, when your object is serialized and then saved to the hard disk, but later changed the field of the class (increase or decrease), when you deserialize, there will be exception, which will cause the problem of incompatibility. But when Serialversionuid is the same, it will deserialize the different field with the default value of type, which avoids the incompatibility problem.
Java (31)-serialization for deep cloning