Java serialization serializable specific explanations (with specific examples)

Source: Internet
Author: User

Java serialization serializable specific explanations (with specific examples)

1. What is serialization and deserialization
serialization (serialization) is a description of an object in a series of bytes. The process of deserializing deserialization is a process of re-building these bytes into an object.


2, under what circumstances need to serialize
A) When you want to save an 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 achieve serialization

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


4. Serialization and deserialization examples

Suppose 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, it is only necessary to invoke 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 () to do so.

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";p rivate int age=24;public static void main (string[] args) {/ The following code implements the serialization of the try {objectoutputstream oos = new ObjectOutputStream (New FileOutputStream ("My.out"));//The output stream holds the file name My.out The ObjectOutputStream can output an object as a byte stream myTest mytest=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 ()//deserialization procedure {ObjectInputStream oin = null;//local variable must be initialized Try{oin = new Objectin Putstream (New FileInputStream ("My.out")); catch (FileNotFoundException E1) {e1.printstacktrace ();} catCH (ioexception E1) {e1.printstacktrace ();} MyTest MTS = null;try {MTS = (MyTest) oin.readobject ();//From Object to MyTest object} catch (ClassNotFoundException e) {E.prin Tstacktrace ();}              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 padded. Look at the output of the deserialization first, such as the following:

Name=sheepmu
Age=24


5. Serialization ID

The serialization ID provides two build strategies under Eclipse, one fixed 1L, and one that randomly generates a long type of data that is not repeated (actually generated using the JDK tool). Here's a suggestion that, assuming there is no special requirement, it is possible to use the default 1L, which will ensure that the code is consistent when the deserialization succeeds. This can also be the cause of serialization and deserialization failures. Because the 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

< Span style= "Font-family:verdana; line-height:22px "> The address of the object before and after serialization is different, but the content is the same. And the references included in the object are the same.

In other words, with serialization, we are able to implement deep copy of any object that can be serializable-which means we are replicating the entire object net. Rather than 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 simply serializing the object into a single stream will restore the same object net as we wrote it, and only in the same stream. Objects are all the same.

< Span style= "Font-family:verdana; line-height:22px ">

7. Whether static variables can 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 examples:

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";p rivate static int age=24;public static void main (string[] args) {//The following code implements the serialization of the try {objectoutputstream oos = new ObjectOutputStream (New FileOutputStream ("My.out"));//The output stream holds a file name called My.out. ObjectOutputStream can output an object as a byte stream myTest mytest=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 to change part age=1; //!!!!!!!!!!!!!!!!!!! Focus on these two lines change part objectinputstream oin = null;//local variable must be initialized Try{oin = new ObJectinputstream (New FileInputStream ("My.out"));              catch (FileNotFoundException E1) {e1.printstacktrace ();} catch (IOException E1) {e1.printstacktrace ();} MyTest MTS = null;try {MTS = (MyTest) oin.readobject ();//From Object to MyTest object} catch (ClassNotFoundException e) {E.prin Tstacktrace ();}              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 values to variables, not static, gets the value of the serialization itself. The static one gets the value from the new attachment. 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. This static member field is not included in the serialization information.

When static is added to the top, the output is 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, and it starts later.

8. Summary:

A) When a parent class implements serialization, the subclass itself implements the serialization itself, without the need to explicitly implement the Serializable interface.

b) When an instance variable of an object references another object, serializing the object also serializes the reference object.

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



Java serialization serializable specific explanations (with specific examples)

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.