Java serialization Serializable

Source: Internet
Author: User

1. What is serialization and deserialization
Serialization (serialization) is a process of describing objects in a sequence of bytes, and deserializing deserialization is a process of re-building these bytes into an object.

2. What situations require serialization
A) When you want to save the object in memory in a file or in a database;
b) When you want to use sockets to transfer objects on the network;
c) When you want to transfer objects through RMI;

3. How to implement serialization

It is possible to implement the serializable interface for a class that requires serialization, and there is no method in the serializable interface that can be understood as a token that indicates that the class can be serialized.

4. Examples of serialization and deserialization

If we want to serialize an object, we first create some outputstream (such as FileOutputStream, Bytearrayoutputstream, etc.), These outputstream are then encapsulated in a objectoutputstream. At this point, you simply call the WriteObject () method to serialize the object and send it to OutputStream( Remember: Object serialization is byte-based and cannot use character-based hierarchies such as reader and writer ). The process of deserializing (reverting a sequence to an object) requires that a inputstream (such as FileInputStream, Bytearrayinputstream, and so on) be encapsulated within the ObjectInputStream. Then call ReadObject ().

Package Com.sheepmu;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import java.io.Serializable;    public class MyTest implements serializable{private static final long serialversionuid = 1L;    Private String name= "SHEEPMU";    private int age=24; public static void Main (string[] args) {//The following code implements the serialization of the try {objectoutputstream oos = new Objecto Utputstream (New FileOutputStream ("My.out"));//The output stream holds a file named my.out; ObjectOutputStream can output an object as a byte stream MyTest myTE            St=new MyTest ();             Oos.writeobject (myTest);  Oos.flush (); Buffered stream Oos.close ();        Close stream} catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace (); } fan ();//Call the following deserialization code} public static void Fan ()//anti-Sequence of Procedure {ObjectInputStream oin = null;//local variable must be initialized try {oin = new Objectinputstrea        M (New FileInputStream ("My.out"));        } catch (FileNotFoundException E1) {e1.printstacktrace ();        } catch (IOException E1) {e1.printstacktrace ();        } MyTest MTS = NULL;            try {mts = (MyTest) oin.readobject ();//The object is transformed down to MyTest object} catch (ClassNotFoundException e) {        E.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();             } System.out.println ("Name=" +mts.name);        System.out.println ("age=" +mts.age); }}

A my.out file is generated in the workspace of this project. The serialized content is later filled, followed by the output of the deserialization as follows:

Name=sheepmu
Age=24

5. Serialization ID

The serialization ID provides two build strategies under Eclipse, one fixed 1L, one randomly generating a non-repeating long type of data (actually generated using the JDK tool), where there is a recommendation that, if there is no special requirement, it is available with the default 1L, which ensures that the code is consistent When deserialization succeeds. This can also be the cause of serialization and deserialization failures because different serialization IDs cannot be serialized and deserialized.

6. Relationship of pre-and post-serialized objects

Is it "= =" or equal? Or is it a shallow copy or a deep copy?

Answer: Deep copy, deserialize the restored object address is different from the original address

The address of the object before and after serialization is different, but the content is the same, and the object contains the same references. In other words, with serialization, we can implement deep copy of any serializable object-meaning we replicate the entire object net, not just the base object and its references. For the same-class objects, their addresses are the same, stating that they are the same object, but not the same as the object addresses of other streams. It is also said that as long as the object is serialized into a single stream, it can recover the same object net as we wrote it, and as long as the object is the same in the same stream.

7. Can the static variable be serialized

If you add static to the age variable in the preceding code, the output is still

Name=sheepmu
Age=24

But look at the following example:

Package Com.sheepmu;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.io.serializable;public class MyTest implements serializable{private static fin    Al long serialversionuid = 1L;    Private String name= "SHEEPMU";    private static int age=24; public static void Main (string[] args) {//The following code implements the serialization of the try {objectoutputstream oos = new Objecto Utputstream (New FileOutputStream ("My.out"));//The output stream holds a file named my.out; ObjectOutputStream can output an object as a byte stream MyTest myTE            St=new MyTest ();             Oos.writeobject (myTest);  Oos.flush (); Buffered stream Oos.close ();        Close stream} catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace (); } fan ();//Call the following deserialization code} public static void FAN () {new MyTest (). Name= "sheepmu_1";//!!!!!!!!!!!!!!!! Focus on these two lines change part Age=1;<span style= "Font-family:verdana, ' Ms Song ', Arial, Soong, Microsoft Ya Hei, Helvetica, Sans-serif; ">//!!!!!!!!!!!!!!!!!!! Focus on these two lines of change section </span> objectinputstream oin = null;//Local variables must be initialized try {oin = new Object        InputStream (New FileInputStream ("My.out"));        } catch (FileNotFoundException E1) {e1.printstacktrace ();        } catch (IOException E1) {e1.printstacktrace ();        } MyTest MTS = NULL;            try {mts = (MyTest) oin.readobject ();//The object is transformed down to MyTest object} catch (ClassNotFoundException e) {        E.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();             } System.out.println ("Name=" +mts.name);        System.out.println ("age=" +mts.age); }}

The output is:

Name=sheepmu
Age=1
Why is the age variable of the top code added to static or deserialized by 24? The new code that assigns a value to a variable, not static, gets the value of the serialization itself, while Static gets the new value. Cause: serialization ignores static variables, that is, serialization does not save the state of static variables. static Members are class-level, so they cannot be serialized. That is, serializing the state of the object is not the state of the class. The meaning of this cannot be serialized is that the serialized information does not contain this static member field. When static is added to the top, it is still output 24 because the value is the value assigned when the JVM loads the class. Note:the variable after transient cannot be serialized , but the situation is slightly more complicated, the opening point later.

8. Summary:

A) When a parent class is serialized and the subclass is automatically serialized, no explicit implementation of the serializable interface is required;

b) When an instance variable of an object refers to another object, the object is serialized by serializing it;

c) The variable after static,transient cannot be serialized;

Java serialization Serializable

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.