Java.io.Serializable Analysis

Source: Internet
Author: User
Tags object serialization

Go from blog address: http://www.cnblogs.com/gw811/archive/2012/10/10/2718331.html

  Java API Java.io.Serializable Interface Source code:

1 public interface Serializable {2}

The Java.io.Serializable class enables its serialization functionality by implementing the interface. A class that does not implement a secondary interface cannot serialize or deserialize any of its states. All the subtypes of a serializable class are themselves serializable. The serialized interface has no methods or fields and is used only to identify the semantics of serializable.

The "object serialization" of Java allows you to convert an object that implements the serializable interface into a byte stream, so that you can restore the byte data and reconstruct that object accordingly.

To serialize an object, you must first create a outputstream and then insert it into the objectoutputstream. At this point, you can write the object to OutputStream using the WriteObject () method.

The WriteObject () method is responsible for writing the state of an object of a particular class so that the corresponding ReadObject () method can restore it. By calling Out.defaultwriteobject, you can invoke the default mechanism of the field that holds the Object. The method itself does not need to involve states that belong to its superclass or subclass. The state is saved by writing the fields to ObjectOutputStream by using the WriteObject method or by using DataOutput supported methods for the base data type.

When reading, you have to embed the InputStream into the ObjectInputStream and then call the ReadObject () method. But it's just a reference of an object, so you have to pass it before you use it. The ReadObject () method is responsible for reading and restoring class fields from the stream.  It can call In.defaultreadobject to invoke the default mechanism to restore non-static and non-transient fields of an object. The Defaultreadobject () method uses the information in the stream to allocate the fields of the object that are saved by the corresponding named field in the current object in the stream. This is used to handle situations where a new field needs to be added after the class is developed. The method itself does not need to involve states that belong to its superclass or subclass. The state is saved by writing the fields to ObjectOutputStream by using the WriteObject method or by using DataOutput supported methods for the base data type.

There are a few things to note when serializing:

1: When an object is serialized, only non-static member variables of the object are saved (including variables declared as private), and no member methods and static member variables can be saved.

2: If the member variable of an object is an object, then the data member of the object is also serialized.

3: If a serializable object contains a reference to an object that is not serializable, the entire serialization operation will fail and a notserializableexception will be thrown. We can mark this reference as transient, so the object can still be serialized.

1. What is serialization?

This is simply to preserve the state of the various objects in memory and to read the state of the saved objects again. Although you can save object states in a variety of ways, Java provides you with a mechanism that should be better than your own to preserve the state of objects, which is serialization.

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. What happens when you serialize an object?

Before serialization, each object that is saved in the heap has a corresponding state, the instance variable (instance ariable), such as:

1 foo myfoo = new Foo (), 2 myfoo. SetWidth (PNS), 3 myfoo.setheight (70);

When serialized by the following code, the values of the width and height instance variables (37,70) in the Myfoo object are saved to the Foo.ser file, so that it can be read from the file later and the original object is recreated in the heap. Of course, saving is not only the value of the instance variable of the object, but the JVM also holds some small amount of information, such as the class type, to restore the original object.

1 FileOutputStream fs = new FileOutputStream ("Foo.ser"), 2 objectoutputstream os = new ObjectOutputStream (fs); 3 os.writeOb Ject (Myfoo);

4. Steps for serializing (saving to a file)

  A) make a fileoutputstream

Java code
FileOutputStream fs = new FileOutputStream ("Foo.ser");

  b) Make a ObjectOutputStream

Java code
ObjectOutputStream OS = new ObjectOutputStream (FS);

  c) Write the object

Java code
Os.writeobject (MYOBJECT1);
Os.writeobject (MYOBJECT2);
Os.writeobject (MYOBJECT3);

  d) Close the ObjectOutputStream

Java code
Os.close ();

5. Examples and explanations

 1 public class Box implements Serializable {2 private static final long serialversionuid = -3450064362986273896l; 3 4 private int width; 5 private int height;         6 7 public static void Main (string[] args) {8 box mybox=new box (); 9 mybox.setwidth (50); 10             Mybox.setheight (+); try {fileoutputstream fs=new fileoutputstream ("F:\\foo.ser"); 13             ObjectOutputStream os=new ObjectOutputStream (FS); Os.writeobject (Mybox); Os.close (); 16 FileInputStream fi=new FileInputStream ("F:\\foo.ser"); ObjectInputStream oi=new ObjectInputStream (fi ), Box box= (Box) Oi.readobject (), Oi.close (), System.out.println (box.height+ "," +b Ox.width} catch (Exception e) {e.printstacktrace ();}24}25  T getwidth () {width;28 return}29 public void setwidth (int width) {30       This.width = width;31}32 public int getheight () {return height;34}35 public void Sethe ight (int height) {this.height = height;37}38}

6, the related matters needing attention

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) Not all objects can be serialized, as to why not, there are many reasons, such as:

1. Security reasons, such as an object has Private,public and other fields, for a transmission of the object, such as writing to a file, or RMI transmission, etc., during the serialization of the transfer process, the object's private domain is not protected.
2. Resource allocation reasons, such as the Socket,thread class, can be serialized, transmitted or saved, and cannot be re-allocated, and there is no need to implement this.

Serialversionuid

The serialization runtime is associated with each serializable class using a version number called Serialversionuid, which is used during deserialization to verify that the sender and receiver of the serialized object have loaded a serialization-compatible class for the object. If the serialversionuid of the object's class that the recipient loads differs from the version number of the corresponding sender's class, the deserialization will result InvalidClassException . A serializable class can "serialVersionUID" long explicitly declare its own serialversionuid by declaring a field that is named (the field must be static (static), eventually (final)):

Any-access-modifier static final Long serialversionuid = 42L;

If the serializable class does not explicitly declare Serialversionuid, the serialization runtime calculates the default Serialversionuid value for the class based on the various aspects of the class, as described in the Java (TM) object serialization specification. However, it is strongly recommended that all serializable classes explicitly declare the SERIALVERSIONUID value because the calculation of the default serialversionuid is highly sensitive to the details of the class. Depending on the compiler implementation, the differences can vary widely, which can cause unexpected results in deserialization InvalidClassException . Therefore, to ensure consistency of serialversionuid values across different Java compilers, the serialization class must declare an explicit SERIALVERSIONUID value. It is also strongly recommended that private you use modifiers to display the declaration Serialversionuid, if possible, because this declaration applies only to the direct declaration class-The Serialversionuid field is not useful as an inherited member. An array class cannot declare an explicit serialversionuid, so they always have a default computed value, but the array class does not have a requirement to match the Serialversionuid value.

Java.io.Serializable Analysis

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.