I. The concept of serialization and deserialization
The process of converting an object to a sequence of bytes is called serialization of an object .
The process of reverting a sequence of bytes to an object is called deserialization of the object .
There are two main uses for serialization of objects:
1) The object's byte sequence is permanently saved to the hard disk, usually stored in a file;
2) A sequence of bytes that transmits an object over the network.
In many applications, some objects need to be serialized to leave the memory space and stay on the physical hard disk for long-term storage. For example, the most common is the Web server session object, when there are 100,000 users concurrent access, there may be 100,000 session objects, memory may be unbearable, so the Web container will be some seesion first serialized to the hard disk, and so on, Restore the objects that were saved to the hard disk in memory.
When two processes are communicating remotely, each other can send various types of data. Regardless of the type of data, it is transmitted over the network in the form of a binary sequence. The sender needs to convert the Java object to a sequence of bytes to be transmitted over the network, and the receiver needs to revert the byte sequence back to the Java object.
Twoserialization APIs in the JDK class library
Java.io.ObjectOutputStream represents an object output stream, and its writeobject (object obj) method serializes the Obj object specified by the parameter and writes the resulting sequence of bytes to a target output stream. Java.io.ObjectInputStream represents an object input stream, and its readobject () method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns them.
Only objects of classes that implement the Serializable and externalizable interfaces can be serialized. The Externalizable interface inherits from the serializable interface, and the class that implements the Externalizable interface controls the serialization behavior entirely by itself, whereas classes that implement the serializable interface can take the default serialization method .
Object serialization consists of the following steps:
1) Create an object output stream, which can wrap a different type of target output stream, such as a file output stream;
2) writes an object through the WriteObject () method of the object output stream.
The steps for deserializing an object are as follows:
1) Create an object input stream, which can wrap a different type of source input stream, such as a file input stream;
2) The object is read through the ReadObject () method of the object input stream.
Examples of object serialization and deserialization:
Define a person class to implement the Serializable interface
Importjava.io.Serializable;/*** <p>ClassName:Person<p> * <p>description: Test object serialization and deserialization <p> *@authorXUDP *@version1.0 V * @createTime 2014-6-9 pm 02:33:25*/ Public classPersonImplementsSerializable {/*** Serialization ID*/ Private Static Final LongSerialversionuid = -5809782578272943999l; Private intAge ; PrivateString name; PrivateString sex; Public intGetage () {returnAge ; } PublicString GetName () {returnname; } PublicString Getsex () {returnsex; } Public voidSetage (intAge ) { This. Age =Age ; } Public voidsetName (String name) { This. Name =name; } Public voidsetsex (String sex) { This. Sex =sex; }}Person class
serializing and deserializing a person class object
ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;ImportJava.text.MessageFormat;/*** <p>ClassName:TestObjSerializeAndDeserialize<p> * <p>description: Test object serialization and deserialization <p> * @authorXUDP *@version1.0 V * @createTime 2014-6-9 pm 03:17:25*/ Public classTestobjserializeanddeserialize { Public Static voidMain (string[] args)throwsException {Serializeperson ();//serializing A Person objectPerson P = Deserializeperson ();//anti-sequence Perons objectSystem.out.println (p.tostring); } /*** Methodname:serializeperson * Description: Serialize Person Object *@authorXUDP *@throwsFileNotFoundException *@throwsIOException*/ Private Static voidSerializeperson ()throwsFileNotFoundException, IOException { person person=NewPerson (); Person.setname ("GaCl"); Person.setage (25); Person.setsex (Male); //ObjectOutputStream the object output stream, stores the person object in the E-drive's Person.txt file, and completes the serialization of the Person objectObjectOutputStream oo =NewObjectOutputStream (NewFileOutputStream (NewFile ("E:/person.txt"))); Oo.writeobject (person); System.out.println ("Person object serialization succeeded!" "); Oo.close (); } /*** Methodname:deserializeperson * Description: Anti-Sequence Perons object *@authorXUDP *@return * @throwsException *@throwsIOException*/ Private StaticPerson Deserializeperson ()throwsException, IOException {objectinputstream ois=NewObjectInputStream (NewFileInputStream (NewFile ("E:/person.txt"))); Person Person=(person) ois.readobject (); System.out.println ("The person object was deserialized successfully!" "); returnPerson ; }}View Code
The result of the code operation is as follows:
Third,the role of Serialversionuid
S?e?r?i?a?l? V?e?r?s?i?o? n? U? I? D?:????????????, all the classes that implement the Serializable interface have a static variable that represents the serialized version identifier.
Private static final long serialversionuid
There are two ways to build Serialversionuid:
The serialversionuid generated with the Add default serial version ID is 1L, for example:
Private static final long serialversionuid = 1L;
The serialversionuid generated using the add generated serial version ID is generated based on the class name, interface name, method, and property, for example:
Private static final long serialversionuid = 4603642343377807741L;
classCustomerImplementsSerializable {//serialversionuid not defined in the Customer class PrivateString name; Private intAge ; //the newly added sex attribute PrivateString sex; PublicCustomer (String name,intAge ) { This. Name =name; This. Age =Age ; } PublicCustomer (String name,intage,string Sex) { This. Name =name; This. Age =Age ; This. Sex =sex; } /** @MethodName tostring * @Description rewrite the ToString () method of the object class * @author XUDP * @return String * @s EE java.lang.object#tostring ()*/@Override PublicString toString () {return"Name=" + name + ", age=" +Age ; }}Add Property
The following exception information is thrown when the deserialization operation is performed:
1 Exception in Thread " Main " Java.io.InvalidClassException:Customer;
2 local class Incompatible:
3 stream Classdesc serialversionuid = -88175599799432325,
4 local class serialversionuid =- 5182532647273106745
That is, the class in the file stream and the class in the classpath, that is, the modified class, is incompatible, in security considerations, the program throws an error, and refuses to load. So what if we really have a need to add a field or method after serialization? What should I do? That is to appoint Serialversionuid. In the Testserialversionuid example, the Serialversionuid of the customer class is not specified, and the Java compiler automatically gives the Class A digest algorithm, similar to the fingerprint algorithm, as long as the file has one more space, The resulting UID will be quite different, and it can be guaranteed that in so many classes, the number is unique. So, after adding a field, because there is no explicit serialversionuid, the compiler generated a UID for us, of course, and the previous saved in the file is not the same, so there are 2 serialized version number inconsistent error. Therefore, as long as we specify the Serialversionuid, we can after serialization, to add a field, or method, without affecting the later restore, the restored object can still be used, but also more methods or properties can be used.
Iv. Value of Serialversionuid
The value of Serialversionuid is generated automatically by the Java Runtime Environment based on the internal details of the class. If the source code of the class is modified and then recompiled, the value of the serialversionuid of the newly generated class file may also change. The default value of the Serialversionuid class is entirely dependent on the implementation of the Java compiler, and compiling with different Java compilers for the same class may lead to different serialversionuid and possibly the same. to improve the independence and certainty of serialversionuid, it is strongly recommended that the definition serialversionuid be displayed in a serializable class, giving it a definite value .
There are two uses for explicitly defining SERIALVERSIONUID: 1, in some cases, you want different versions of the class to be serializable compatible, so you need to make sure that different versions of the class have the same serialversionuid, 2, and in some cases, you don't want different versions of the class to be compatible with serialization, so You need to make sure that different versions of the class have different serialversionuid.
Serialization of the Java Foundation