1. All classes that implement serialization must implement a serializable interface, and serialization has the following two features:
- If a class can be serialized, its subclasses can also be serialized
- Because static represents a class member, trasient represents the temporary data for the object, so the data members that are known as these two types cannot be serialized.
2. Examples of serialization and deserialization
PackageStreamlearn;ImportJava.io.*;/*** Created by Liujinhong on 2017/3/6.*//*** Serialization and serialization of instances*/ Public classSerialobjecttest { Public Static voidMain (string[] args) {people P=Newpeople (); ObjectOutputStream Oos=NULL; ObjectInputStream Ois=NULL; //Serialization of Try{FileOutputStream fos=NewFileOutputStream ("/users/liujinhong/desktop/test/ttt"); Oos=NewObjectOutputStream (FOS); Oos.writeobject (P); } Catch(Exception e) {System.out.println (e); } finally { } //deserializationpeople p1; Try{FileInputStream fis=NewFileInputStream ("/users/liujinhong/desktop/test/ttt"); Ois=NewObjectInputStream (FIS); P1=(People) ois.readobject (); System.out.println (p1.a); System.out.println (p1.b); System.out.println (p1.book.id); } Catch(Exception e) {System.out.println (e); } finally { } }}classPeopleImplementsSerializable { Public intA = 1; Public transient intb = 2; PublicBook book =NewBook ();}classBookImplementsSerializable { Public intID = 1;}
3. When do I need to use serialization?
- Sending objects over a network, or the state of an object needs to be persisted into a database or file
- Serialization enables deep replication , which means that referenced objects can be copied
4. Serialversionuid role?
In the process of serialization and deserialization, Serialversionuid plays a very important role, each class has a specific serialversionuid, in the process of deserialization through Serialversionuid to determine the compatibility of the class. If incompatible will run out of the invalidclassexception exception.
5. What are the advantages of customizing Serialversionuid?
- Improve program operation efficiency
- Improve the compatibility of programs on different platforms
- Enhanced compatibility for each version
The serialization mechanism of Java