Analysis of java. io. Serializable

Source: Internet
Author: User
Tags object serialization

Analysis of java. io. Serializable

 

  Java. io. Serializable Interface source code in java API:

1 public interface Serializable {2 }

Class can enable its serialization function by implementing the java. io. Serializable interface. Classes that do not implement secondary interfaces cannot be serialized or deserialized in any State. All sub-types of serializable classes are themselves serializable. The serialization interface has no methods or fields and is only used to identify the serializable semantics.

Java's "Object serialization" allows you to convert an object that implements the Serializable interface into a byte stream, so that you can recover these bytes when using this object in the future, and re-build the object accordingly.

To serialize an object, you must first create an OutputStream and embed it into ObjectOutputStream. In this case, you can use the writeObject () method to write the object into OutputStream.

The writeObject () method is used to write the state of the object of a specific class, so that the corresponding readObject () method can restore it. You can call out. defaultWriteObject to call the default mechanism for saving the fields of the Object. This method does not need to involve the status of its superclass or subclasses. The status is saved by writing fields into ObjectOutputStream using the writeObject method or the method supported by DataOutput for basic data types.

During reading, you must embed InputStream into ObjectInputStream and then call the readObject () method. However, this is only the reference of an Object. Therefore, you have to upload the Object first before using it. The readObject () method reads and restores class fields from the stream. It can call in. defaultReadObject to call the default mechanism to restore non-static and non-transient fields of the object. The defaultReadObject () method uses the information in the stream to allocate the fields of the objects saved through the corresponding named fields in the current object in the stream. This is used when new fields need to be added after the class is developed. This method does not need to involve the status of its superclass or subclasses. The status is saved by writing fields into ObjectOutputStream using the writeObject method or the method supported by DataOutput for basic data types.

Pay attention to the following points during serialization:

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

2: If the member variable of an object is an object, the data member of this object will also be serialized.

3: If a serializable object contains a reference to a non-serializable object, 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?

To put it simplyStatus of various objects stored in memoryAnd read the status of the saved object. Although you can use your own methods to save Object States, Java provides you with a mechanism better than your own to save the Object state, that is, serialization.

2. Under what circumstances should serialization be performed?

A) when you want to save the objects in the memory to a file or database;
B) when you want to use a socket to transmit objects over the network;
C) when you want to transmit objects through RMI;

3. What happens when an object is serialized?

Before serialization, each object stored in Heap has a corresponding state, that is, instance ariable, for example:

1 Foo myFoo = new Foo();2 myFoo .setWidth(37);3 myFoo.setHeight(70);

After the following code is serialized, the values of the width and Height instance variables () in the MyFoo object are saved to foo. in the ser file, you can read it from the file and create the original object in the heap. Of course, it is not only to save the instance variable value of the object, but also to save a small amount of information, such as the type of the class, to restore the original object.

1 FileOutputStream fs = new FileOutputStream("foo.ser");2 ObjectOutputStream os = new ObjectOutputStream(fs);3 os.writeObject(myFoo);

4. serialize (save 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

 

 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(30);11         try {12             FileOutputStream fs=new FileOutputStream("F:\\foo.ser");13             ObjectOutputStream os=new ObjectOutputStream(fs);14             os.writeObject(myBox);15             os.close();16             FileInputStream fi=new FileInputStream("F:\\foo.ser");17             ObjectInputStream oi=new ObjectInputStream(fi);18             Box box=(Box)oi.readObject();19             oi.close();20             System.out.println(box.height+","+box.width);21         } catch (Exception e) {22             e.printStackTrace();23         }24     }25     26     public int getWidth() {27         return width;28     }29     public void setWidth(int width) {30         this.width = width;31     }32     public int getHeight() {33         return height;34     }35     public void setHeight(int height) {36         this.height = height;37     }38 }

6. Precautions

A) when a parent class is serialized, the Child class automatically serializes without explicitly implementing the Serializable interface;
B) when the instance variable of an object references other objects, the referenced object is also serialized when the object is serialized;
C) Not all objects can be serialized. As for why not, there are many reasons, such:

1. security reasons: for example, an object has fields such as private and public. For an object to be transmitted, such as writing to a file, or performing rmi transmission, during serialization and transmission, the private and other fields of this object are not protected.
2. the reason for resource allocation, such as socket and thread classes, cannot be re-allocated if they can be serialized, transmitted, or saved. In addition, there is no need for such implementation.

 

SerialVersionUID

During serialization, a version number called serialVersionUID is used to associate with each serializable class, in the deserialization process, this serial number is used to verify whether the sender and receiver of the serialized object have loaded classes compatible with serialization for this object. If the serialVersionUID of the class loaded by the receiver is different from the version of the class of the corresponding sender, deserialization will causeInvalidClassException. The serializable class can be declared"serialVersionUID"(This field must be static and final)longType field) explicitly declare its own serialVersionUID:

 ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

If the serialVersionUID is not explicitly declared for the serializable class, the default serialVersionUID value of the class is calculated based on all aspects of the class during the serialization runtime, as described in "Java (TM) Object serialization specification. However,Strongly recommendedAll serializable classes explicitly declare the serialVersionUID ValueThe reason is that the calculation of the default serialVersionUID is highly sensitive to the detailed information of the class. The differences may vary depending on the implementation of the compiler, which may cause exceptions in the deserialization process.InvalidClassException. Therefore, to ensure the consistency of serialVersionUID values across different java compilers, the serialization class must declare a clear serialVersionUID value. We strongly recommend that you useprivateThe modifier displays the Declaration serialVersionUID (if possible), because this declaration is only applicable to the direct Declaration class -- serialVersionUID field as an inherited member. The array class cannot declare a clear serialVersionUID, so they always have the default calculated value, but the array class does not match the serialVersionUID value.

 

 

 

 

 

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.