Java Serializable (serialization) of the understanding and summary of the specific implementation process

Source: Internet
Author: User
Tags object serialization

Original address:

Java Serializable (serialization) of the understanding and summary of the specific implementation process

How does an in-memory object exist?  What is the state of the various objects in memory?    What is an instance variable (refers to an instantiated object)? What are the benefits of using serialization?

1. What is serialization?
This is simply to preserve the state of various objects in memory (i.e., instance variables, not methods), and to read the saved object state 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 state of 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. 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:
Java code
1. foo myfoo = new Foo ();
2. Myfoo. SetWidth (37);
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.dat 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.
Java code
1. FileOutputStream fs = new FileOutputStream ("Foo.dat");
2. ObjectOutputStream os = new ObjectOutputStream (FS);
3. Os.writeobject (Myfoo);

4. Steps for serializing (saving to a file)
A) make a fileoutputstream
Java code

1. FileOutputStream fs = new FileOutputStream ("Foo.ser");

b) Make a ObjectOutputStream
Java code

1. ObjectOutputStream os = new ObjectOutputStream (FS);

c) Write the object

Java code
1. Os.writeobject (MYOBJECT1);

d) Close the ObjectOutputStream

Java code
1. Os.close ();

5. Examples and explanations
Java code

1. Import*;
4. Public class Box implements Serializable
5. {
6. private int width;
7. private int height;
9. public void setwidth (int width) {
Ten. This.width = width;
public void setheight (int height) {
This.height = height;
public static void Main (string[] args) {
Box Mybox = new box ();
Mybox.setwidth (50);
Mybox.setheight (30);
FileOutputStream fs = new FileOutputStream ("Foo.ser");
ObjectOutputStream OS = new ObjectOutputStream (FS);
Os.writeobject (Mybox);
Os.close ();
}catch (Exception ex) {
Ex.printstacktrace ();

6, the related matters needing attention
A) When serializing, only the state of the object is saved, regardless of the object's method;
b) When a parent class is serialized and the subclass is automatically serialized, no explicit implementation of the serializable interface is required;
c) When an instance variable of an object refers to another object, the object is serialized as well.
D) 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.

What serialization is:
Serialization is the preservation of the state of an object (the amount of each property), which is then obtained at the appropriate time.
Serialization consists of two parts: serialization and deserialization. Serialization is the first part of this process that decomposes data into byte streams to
stored in a file or transmitted over a network. Deserialization is the opening of a byte stream and refactoring the object. Object serialization not only converts the base data type to a byte representation, but sometimes restores the data. Recovering data requires an object instance with recovery data
What are the characteristics of serialization:
If a class can be serialized, its subclasses can also be serialized. member data declared as static and transient types cannot be serialized. Because static represents the state of a class, transient represents the temporary data for the object.
When to use serialization:
One: Object serialization can implement distributed objects. Main applications For example: RMI to use object serialization to run a service on a remote host, just as you would when running an object on a local machine.
Two: Java object serialization preserves not only the data of an object, but also the data of each object referenced by the object. You can write the entire object hierarchy to a stream of bytes that can be saved in a file or passed on a network connection. Object serialization allows you to "deep copy" the object, which is to copy the object itself and the referenced object itself. Serializing an object may get the entire sequence of objects.
Class by implementing the interface to enable its serialization functionality. Classes that do not implement this interface will not be able to serialize or deserialize any of their 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.
To allow the serialization of a subtype of a non-serializable class, you can assume that the subtype is responsible for saving and restoring the state of the super-type common (public), protected (protected), and (if accessible) package fields. It is assumed that a subtype has this responsibility only if a class with a subtype extension has an accessible parameterless construction method to initialize the state of the class. If this is not the case, it is an error to declare that a class is a serializable class. This error will be detected at run time.
During deserialization, the fields of the non-serializable class are initialized using the class's public or protected parameterless construction method. A serializable subclass must have access to a parameterless construction method. The fields of the serializable subclass are restored from the stream.
When traversing a graph, you may encounter objects that do not support serializable interfaces. In this situation, the notserializableexception is thrown and the class that identifies the non-serializable object is identified.
Classes that require special handling during serialization and deserialization must use the following exact signatures to implement special methods:
The WriteObject method is responsible for writing the state of the object of a particular class so that the appropriate 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.
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.
When you write an object to a stream, you need to specify the serializable class of the alternative object that you want to use, and you should use an accurate signature to implement this particular method:
This writereplace method will be called by serialization, if this method exists, and it can be accessed through a method defined in the class of the object being serialized. Therefore, the method can have private (private), protected (protected), and packet-private (package-private) access. Subclasses access to this method follows the Java access rules.
When you read an instance of a class from a stream, you need to specify the exact signature that the alternative class should use to implement this special method.
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, deserialization will cause invalidclassexception. A serializable class can explicitly declare its own serialversionuid by declaring a field named "Serialversionuid", which must be a static (static), final (final) long field:
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, such 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 default serialversionuid is highly sensitive to the details of the class and may vary depending on the compiler implementation. This can lead to unexpected invalidclassexception during deserialization. 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 to use the private modifier to display the declaration Serialversionuid, if possible, because such a claim is not useful for declaring the class--serialversionuid field as an inherited member only immediately. the problem-what is serialization? Under what circumstances will the class be serialized?
Serialization is a mechanism for dealing with the flow of objects, so-called object flow is the flow of the object's contents. It is possible to read and write to a Fluidized object, or to transfer the streamed object between the networks. Serialization is a problem that is raised when reading and writing to an object stream. Serialization implementation: Implement the Serializable interface for the class that needs to be serialized, there is no method to implement, implementsserializable just to annotate that the object is serializable, and then use an output stream ( such as: FileOutputStream) to construct a ObjectOutputStream (object flow) object, followed by the WriteObject (objectobj) of the ObjectOutputStream object method to write out (that is, save its state) the object with the parameter obj, and the input stream to restore.
Serialization: Serialization is the process of converting an object into a format that is easy to transfer. For example, you can serialize an object and then use HTTP over the Internet on the client and
Transfer the object between servers. At the other end, deserialization reconstructs the object from the stream.
is a mechanism for object persistence.
Specifically, the object should be serialized, the general program at run time, the object is generated, these objects disappear as the program stops running, but if we want to put some objects (because it is the object, so there are different characteristics) to save, after the program terminates, these objects still exist, You can read the values of these objects while the program is running again, or take advantage of these saved objects in other programs. In this case, the serialization of the object is used.
Only the serialized object can
The serialized object is removed from the server's hard disk, then transmitted to the client via the network, and the serialized object is read into memory by the client, and the corresponding processing is performed.
Object serialization is a feature of Java that allows objects to be written into a set of bytecode that, when read in other locations, creates a new object, and the state of the new object is exactly the same as the original object. In order to implement object serialization, it is necessary to have access to the private variables of the class, so that the object state can be saved and restored correctly. Accordingly, the object serialization API is able to restore these values to a private data member when the object is rebuilt. This is a challenge to access permissions for the Java language. Objects that are typically used in server clients
Exchange above, the other is in the native storage.
The most important use of object serialization is to guarantee the integrity and transitivity of objects when passing, and saving objects (object). For example, when transmitting over a network, or storing an object as a file, the serialization interface is implemented.
Even if you have not used object serialization (serialization), you may also know it. But do you know
Java also supports another form of object persistence, externality (externalization)?
Here's how serialization and externalities are associated at the code level:
The main differences between serialization and externalities
Externalities and serialization are two different ways to achieve the same goal. Let's examine the main differences between serialization and externalities.
Support for object serialization through the serializable interface is built into the core API, but all implementations must provide read and write-out implementations. Java already has built-in support for serialization, meaning that if you make your own class,java you will try to store and reorganize your objects. If you use externalities, you can choose to do the work of reading and writing entirely by yourself, and the only support Java provides to the externality is the interface:
Serialization automatically stores the necessary information to deserialize the stored instance, and the externality saves only the identity of the stored class. When you serialize an object through the interface, information about the class, such as its properties and the types of those properties, is stored together with the instance data. Java only stores very little information about each of the stored types when you choose to go externalizable this way.
Advantages and disadvantages of each interface
Java Advantages: built-in support
• Advantages: Easy to implement
• Cons: Too much space occupied
• Cons: Slower speed due to extra overhead
• Pros: Less overhead (programmers decide what to store)
• Advantages: Possible speed improvements
• Cons: Virtual machines do not provide any help, which means that all work falls on the developer's shoulders.
How to choose between the two depends on the application's needs. Serializable is usually the simplest solution, but it can lead to unacceptable performance issues or space problems, and in the case of these problems, externalizable can be a viable path.
One thing to keep in mind is that if a class is externalizable, then the Externalizable method will be used to serialize instances of the class, even if the type provides the Serializable method:

Java Serializable (serialization) understanding and summary, implementation process (RPM)

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: 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.