A detailed explanation of object serialization and deserialization in Java _java

Source: Internet
Author: User
Tags modifier object serialization serialization

This article illustrates the serialization and deserialization of objects in Java. Share to everyone for your reference. Specifically as follows:

First, Introduction

Object Serialization (Serializable) is the process of converting an object to a sequence of bytes, while deserialization is the process of recovering an object based on a byte sequence.

Serialization is generally used for the following scenarios:

1. Permanently save the object, save the object's byte sequence to the local file;
2. Passing objects over the network through serialization objects;
3. Passing objects between processes through serialization.

The class to which the object belongs must implement a serializable or Externalizable interface to be serialized. For the class that implements the Serializable interface, its serialization and deserialization adopt the default serialization method, the Externalizable interface inherits the interface of the serializable interface, and is the extension of the serializable, The class that implements the Externalizable interface completely controls the serialization and deserialization behavior.

Java.io.ObjectOutputStream represents an object output stream, its method writeobject (object obj) enables serialization of the object and writes the resulting byte sequence to the target output stream.

Java.io.ObjectInputStream represents an object input stream whose ReadObject () method reads a sequence of bytes from the source input stream, deserializes it into an object, and returns it.

Two, several ways of serialization

Suppose you define a customer class that, depending on how the customer implements serialization, may have the following serialization methods:

1. Implement serializable, undefined ReadObject and WriteObject methods

ObjectOutputStream uses JDK defaults to serialize the transient instance variables of the customer object;
ObjectInputStream uses JDK defaults to deserialize a transient instance variable of a customer object.

2. Implement serializable and define the ReadObject and WriteObject methods

ObjectOutputStream invokes the WriteObject (ObjectOutputStream out) method of the customer class to serialize the non-transient instance variables of the customer object;
ObjectInputStream invokes the ReadObject (ObjectInputStream in) method of the customer class to deserialize a non-transient instance variable of the Customer object.

3. Implement externalizable, define Readexternal and Writeexternal methods

ObjectOutputStream the Writeexternal method of the customer class to serialize the non transient instance variables of the customer object;
ObjectInputStream first instantiate an object by using the parameterless constructor of the customer class, and then deserialize the transient instance variable of the customer object with the Readexternal method.

Three, Serializable interface

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

During deserialization, fields that are not serializable are initialized with the public or protected parameterless construction method of the class. A serializable subclass must have access to a parameterless construction method. The fields of the serializable subclass are recovered from the stream.

When you traverse a Class View, you may encounter objects that do not support the Serializable interface. In this case, the notserializableexception is thrown and the class of the object that is not serializable is identified.

1. Accurate signature

Classes that require special handling during serialization and deserialization must implement special methods using the following exact signature:

private void WriteObject (Java.io.ObjectOutputStream out) throws IOException
private void ReadObject (Java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;
private void Readobjectnodata () throws objectstreamexception;

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

The ReadObject method is responsible for reading and recovering class fields from the stream. It can invoke the In.defaultreadobject to invoke the default mechanism to restore the non-static and transient fields of the object. The Defaultreadobject method uses the information in the stream to allocate fields in the stream that are saved by the corresponding specified field in the current object. This is used to handle situations where a new field needs to be added after the class evolves. The method itself does not need to involve states that belong to its superclass or subclass. States can be saved by writing each field to ObjectOutputStream by using the WriteObject method or by using a method supported by DataOutput for the base data type.

The Readobjectnodata method is responsible for initializing the object state of a particular class in cases where the serialization stream does not list the given class as a superclass that will be deserialized. This occurs when the version of the deserialized instance class used by the receiver differs from the sender, and the recipient version-extended class is not a class that is extended by the sender version. Occurs when the serialized stream has been tampered with, so the Readobjectnodata method can be used to properly initialize the deserialized object, regardless of whether the source is "hostile" or incomplete.

When you write an object to a stream, you need to specify the serializable class of the alternate object to use, and you should use an exact signature to implement this particular method:

Any-access-modifier Object Writereplace () throws objectstreamexception;
This writereplace method is called by serialization if the method exists, and it can be accessed through a method defined in the class of the serialized object. Therefore, the method can have private (private), protected (protected), and package private (package-private) access. Subclasses access to this method follow Java access rules.

When you read an instance of a class from the stream, you need to specify the exact signature that the alternative class should use to implement this particular method.

Any-access-modifier Object Readresolve () throws objectstreamexception;
This readresolve method follows the same invocation rules and access rules as writereplace.
If a class defines the Readresolve method, the Readresolve method is called at the end of deserialization, and the object returned by the method is the final result of deserialization.

2.serialVersionUID

The serialization runtime uses a version number called Serialversionuid that is associated with each serializable class, which is used during deserialization to verify that the sender and receiver of the serialized object loaded the serialization-compatible class for the object. If the serialversionuid of the class of the object loaded by the recipient differs from the version number of the corresponding sender's class, deserialization will cause invalidclassexception. A serializable class can explicitly declare its own serialversionuid by declaring a field that is named "Serialversionuid" (the field must be static (static), final (final) long field):
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 of the class based on various aspects of the class, as described in "Java (TM) object serialization specification." However, it is strongly recommended that all serializable classes explicitly declare SERIALVERSIONUID values because the calculation of the default serialversionuid is highly sensitive to the details of the class and can vary depending on the compiler implementation. This can result in unexpected invalidclassexception during deserialization. Therefore, to ensure consistency of serialversionuid values across different Java compilers, the serialization class must declare a clear serialversionuid value. It is also strongly recommended that you use the private modifier to display the declaration Serialversionuid, if possible, because such a declaration applies only to declaring the class directly--the Serialversionuid field is not useful as an inherited member. Array classes cannot declare a clear serialversionuid, so they always have default computed values, but array classes do not have a matching Serialversionuid value requirement.

3.Externalizable interface

Externalizable is an extension of serailizable, which implements the serialization of Externalizable interfaces with the following characteristics:
The method of calling the class is writeexternal when serializing, and the Readexternal method is called by deserialization;
The parameterless constructor of the class is invoked first when deserialization is performed, which is different from the default deserialization, so that the class that implements the serialization of the Externalizable interface must provide a public parameterless constructor, otherwise the exception will occur when deserializing.

Iv. Summary

If the default serialization method is used, the instance can be serialized as long as a class implements the Serializable interface. Typically, classes designed specifically for inheritance should try not to implement the serializable interface, because once the parent class implements the Serializable interface, all of its subclasses are serializable as well.

Disadvantages of the default serialization method:

1. It is not safe to serialize sensitive data directly to the object which is not suitable for external disclosure;
2. Does not check whether the object's member variable conforms to the correct constraint condition, may be tampered with the data and cause the running exception;
3. The object graph needs to do recursively traversal, if the object graph is very complex, will consume many resources, the setting causes the Java Virtual machine stack overflow;
4. Make the interface of class be constrained by the internal implementation of class, and restrict the upgrade and maintenance of class.

By implementing the private type of writeobject () and ReadObject () of the Serializable interface, or by implementing the Externalizable interface, and implementing Writeexternal () and readexternal () method, and provide the public type parameterless constructor two ways to control the serialization process can effectively circumvent the default serialization method of the deficiencies.

I hope this article will help you with your Java programming.

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.