1. 必须implements Serializable;
2. The basic algorithm is:
a. Write out the meta data of the current class
b. Write out recursively until java.lang.Object, the meta data of the parent class
c. Write out instance field information
3. If a field in the class cannot be serialized, or does not require serialization, mark the field as transient. Except for other fields of transient, including private, they will be serialized;
4. For serialized objects, adding/reducing fields or methods, deserialization will report java.io.InvalidClassException; if such changes are compatible, you can provide a field serialVersionUID, given a certain value; if If the level of the class has changed, it cannot be deserialized;
5. Object serialization and deserialization can be done by calling ObjectInputStream.readObject()/ObjectOutputStream.writeObject
FileOutputStream fos = new FileOutputStream("temp.out");
ObjectOutputStream oos = new ObjectOutputStream(fos);
SerialTest st = new SerialTest();
oos.writeObject(st);
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream("temp.out");
ObjectInputStream oin = new ObjectInputStream(fis);
TestSerial ts = (TestSerial) oin.readObject();
System.out.println("version="+ts.version);
6. If you want more control over serialization, you can implement the following methods:
private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;
refer to:
1. https://www.javaworld.com/article/2072752/the-java-serialization-algorithm-revealed.html
2. http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html