1. What is serialization? Why serialize?
Java serialization refers to the process of converting an object to a sequence of bytes, whereas deserialization is the process of converting a sequence of bytes into a target object only.
We all know that in the browser access, we see the text, images, audio, video, etc. are transmitted through a binary sequence, so if we need to transfer the Java object, should we also first serialize the object? The answer is yes, we need to first serialize the Java object, and then through the network, IO transmission, when the destination, and then deserialization to get to the object we want, and finally complete the communication.
2. How to implement serialization
2.1. Use the key classes ObjectOutputStream and ObjectInputStream in the JDK
ObjectOutputStream class: Writes an object in binary format by using the WriteObject (Object object) method.
ObjectInputStream class: By using the ReadObject () method, the binary stream is read from the input stream and converted to an object.
2.2. Target objects need to implement the seriable interface First
We create a student class:
Public classStudentImplementsSerializable {Private Static Final LongSerialversionuid = 3404072173323892464L; PrivateString name; Private transientString ID; PrivateString age; @Override PublicString toString () {return"student{" + "name=" + name + ' \ ' + ", id= ' + ID + ' \ ' +", age= ' "+ Age + ' \ ' + '} '; } PublicString getage () {returnAge ; } Public voidsetage (String age) { This. Age =Age ; } PublicStudent (string name, string id) {SYSTEM.OUT.PRINTLN ("Args Constructor"); This. Name =name; This. ID =ID; } PublicStudent () {System.out.println ("None-arg Constructor"); } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString getId () {returnID; } Public voidsetId (String id) { This. ID =ID; }}
The student class in the code implements the serializable interface and generates a version number:
Private static final long serialversionuid = 3404072173323892464L;
First of all:
1. The function of theSerializable interface is only used to identify that our class needs to be serialized, and no method is provided in the Serializable interface.
2,serialversionuid serialization version number is used to distinguish between the version of the class we write, to determine whether the version of the class at the time of deserialization is always, if inconsistent, there will be a version inconsistency exception.
3,transient keyword , mainly used to ignore the variables we do not want to serialize
2.3. Sequence or deserialize an object
2.3.1 The first write method:
Public Static voidMain (string[] args) {File file=NewFile ("D:/test.txt"); Student Student=NewStudent ("Monkey King", "12"); Try{ObjectOutputStream OutputStream=NewObjectOutputStream (Newfileoutputstream (file)); Outputstream.writeobject (student); Outputstream.close (); } Catch(IOException e) {e.printstacktrace (); } Try{ObjectInputStream ObjectInputStream=NewObjectInputStream (Newfileinputstream (file)); Student s=(Student) objectinputstream.readobject (); System.out.println (S.tostring ()); System.out.println (S.equals (student)); } Catch(IOException e) {e.printstacktrace (); } Catch(ClassNotFoundException e) {e.printstacktrace (); } }
Create an object student, and then output the object to a file by using the WriteObject () method in the ObjectOutputStream class.
The object is then deserialized by the ReadObject () method in the ObjectInputStream class.
2.3.2 Second Write Method:
Implement the WriteObject () and ReadObject () methods in the Student class:
Private void throws IOException { objectoutputstream.defaultwriteobject (); Objectoutputstream.writeutf (ID); } Private void throws IOException, ClassNotFoundException { objectinputstream.defaultreadobject (); = Objectinputstream.readutf (); }
In this way, we can customize the variables we want to serialize, stream input streams and outputs into the alignment instance, and serialize and deserialize them.
2.3.3 The third Way of writing:
Student implement Externalnalizable interface without implementing Serializable interface
The Externaliable interface is a subclass of Serializable, with the same functionality as the Serializable interface:
Public classStudentImplementsexternalizable {Private Static Final LongSerialversionuid = 3404072173323892464L; PrivateString name; Private transientString ID; PrivateString age; @Override PublicString toString () {return"student{" + "name=" + name + ' \ ' + ", id= ' + ID + ' \ ' +", age= ' "+ Age + ' \ ' + '} '; } PublicString getage () {returnAge ; } Public voidsetage (String age) { This. Age =Age ; } PublicStudent (string name, string id) {SYSTEM.OUT.PRINTLN ("Args Constructor"); This. Name =name; This. ID =ID; } PublicStudent () {System.out.println ("None-arg Constructor"); } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString getId () {returnID; } Public voidsetId (String id) { This. ID =ID; } @Override Public voidWriteexternal (ObjectOutput out)throwsIOException {out.writeobject (name); Out.writeobject (ID); } @Override Public voidReadexternal (ObjectInput in)throwsIOException, classnotfoundexception {name=(String) in.readobject (); ID=(String) in. ReadObject (); }}
By comparing with the previous second write method, we can find that their implementation principle is very similar, but the implementation of the Externalnalizable interface does not support the first serialization method, it can only be implemented through the interface Writeexternal () and the Readexternal () method to implement the serialization of the object.
3. Questions about serialization during the interview:
1, what is serialization, how to implement serialization
The serialization of objects in Java is the conversion of an object into a binary sequence, and deserialization is the conversion of a binary sequence into an object
There are several ways in which Java implements serialization
1, first need to use to the tool class ObjectInputStream and ObjectOutputStream two IO class
2. Implement serializable interface:
There are two kinds of specific serialization methods:
2.1 Directly through the WriteObject () and ReadObject () methods in the ObjectOutputStream and ObjectInputStream classes
2.2 To complete serialization by implementing the WriteObject () and ReadObject () methods in the serialized object, passing in the ObjectOutputStream and ObjectInputStream objects
3. Implement Externalizable Interface:
Can only implement serialization of objects by implementing the Writeexternal () and Readexternal () methods in the interface
2, transient keywords? How do I serialize a variable that is decorated with the transient modifier?
The role of transient is to block variables that we do not want to serialize, which are ignored by the object during serialization and deserialization sessions.
We can invoke the writeUTF () and readUTF () methods of the output stream or input stream in the method by implementing the WriteObject and ReadObject methods in the serialization method described above.
or by implementing the Externalizable interface, implement the Writeexternal () and Readexternal () methods before customizing the sequence session object.
3, how to ensure that the serialization and deserialization of the object consistent? (If you have any objection)
After reviewing some of the data, I found that it is not guaranteed that the objects after serialization and deserialization are consistent, because in the process of deserialization, we first create an object,
The object is then deserialized by assigning a value to the object, so the problem is that after a new object is created, the object reference and the original object do not point to the same target.
So we can only guarantee that their data and versions are consistent, and that they do not guarantee the consistency of the objects.
Serialization and deserialization of Java