Use of the Java serialization interface serializable

Source: Internet
Author: User
Tags object serialization

From: http://wang09si.blog.163.com/blog/static/170171804201373195046397/

The first thing to understand is, what is serialization?
We often see an entity class implement the Serializable interface, and this usage is serialization. The goal is to save the state of the object so that it can be read out.
Serialization is the preservation of the state of an object (the amount of each property), which is then obtained at the appropriate time.
Serialization decomposes data into a byte stream for storage in a file or for transmission 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
Java provides us with a better mechanism for preserving object state, which is serialization.
That is to say, save state and read State of things Java has done for us, we just need to adjust the corresponding method on it.

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.

The

next to figure out, under what circumstances need to instantiate?
 1, when you want to save the state of the object in memory to a file or database,
 2, when you want to use sockets to transfer objects on the network;
 java object serialization preserves not only the data of an object, And recursively holds the data for 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.
 3, when you want to transfer objects through RMI,
 rmi to run the service on the remote host with object serialization just as you would when running the object on a local machine.


Finally, how is serialization implemented?
Before serialization, each object that is saved in the heap has a corresponding state, the instance variable (instance ariable), such as:
Foo myfoo = new Foo ();
Myfoo. SetWidth (37);
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.
FileOutputStream fs = new FileOutputStream ("Foo.ser");
ObjectOutputStream OS = new ObjectOutputStream (FS);
Os.writeobject (Mybox);
Os.close ();

ObjectInputStream in = new ObjectInputStream (New FileInputStream ("Foo.ser"));
Box box = (box) (In.readobject ());
System.out.println (Box.tostring ());
System.out.println (Box.height);
In.close ();

Complete Example:
Package wzq.j2se.erializables;

Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import java.io.Serializable;

public class Box implements Serializable {
private int width;
private int height;

public void setwidth (int width) {
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);
  try {
   fileoutputstream fs = new FileOutputStream ("Foo.ser");
   objectoutputstream OS = new ObjectOutputStream (FS);
   os.writeobject (Mybox);
   os.close ();
   
   objectinputstream in = new ObjectInputStream (New FileInputStream (" Foo.ser "));
   box box = (box) (In.readobject ());
   system.out.println (box.tostring ());
   system.out.println (box.height);
   in.close ();
  } catch (Exception ex) {
   ex.printstacktrace ();
  }
 }
}//WriteObject and ReadObject are thread-safe in nature and are not allowed to be accessed concurrently during transmission. So the object can be passed one after the other.



Subclass:

Package wzq.j2se.erializables;

Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;

public class Extendsbox extends box{
int age;

public int getage () {
return age;
}

public void Setage (int.) {
This.age = age;
}

public static void Main (string[] args) {
Extendsbox EB = new Extendsbox ();
Eb.setage (101);
try {
FileOutputStream fs = new FileOutputStream ("abc");
ObjectOutputStream OS = new ObjectOutputStream (FS);
Os.writeobject (EB);
Os.close ();

ObjectInputStream in = new ObjectInputStream (New FileInputStream ("abc"));
Extendsbox box = (Extendsbox) (In.readobject ());
System.out.println (Box.tostring ());
System.out.println (Box.getage ());
In.close ();
} catch (Exception ex) {
Ex.printstacktrace ();
}
}
}


The first thing to understand is, what is serialization?
We often see an entity class implement the Serializable interface, and this usage is serialization. The goal is to save the state of the object so that it can be read out.
Serialization is the preservation of the state of an object (the amount of each property), which is then obtained at the appropriate time.
Serialization decomposes data into a byte stream for storage in a file or for transmission 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
Java provides us with a better mechanism for preserving object state, which is serialization.
That is to say, save state and read State of things Java has done for us, we just need to adjust the corresponding method on it.

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.

Second, to figure out, under what circumstances need to instantiate?
1. When you want to save the state of the object in memory to a file or database;
2. When you want to use sockets to transfer objects on the network;
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.
3, when you want to transfer the object through RMI;
RMI to use object serialization to run a service on a remote host, just as it would when running an object on a local machine.


Finally, how is serialization implemented?
Before serialization, each object that is saved in the heap has a corresponding state, the instance variable (instance ariable), such as:
Foo myfoo = new Foo ();
Myfoo. SetWidth (37);
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.
FileOutputStream fs = new FileOutputStream ("Foo.ser");
ObjectOutputStream OS = new ObjectOutputStream (FS);
Os.writeobject (Mybox);
Os.close ();

ObjectInputStream in = new ObjectInputStream (New FileInputStream ("Foo.ser"));
Box box = (box) (In.readobject ());
System.out.println (Box.tostring ());
System.out.println (Box.height);
In.close ();

Complete Example:
Package wzq.j2se.erializables;

Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import java.io.Serializable;

public class Box implements Serializable {
private int width;
private int height;

public void setwidth (int width) {
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);
try {
FileOutputStream fs = new FileOutputStream ("Foo.ser");
ObjectOutputStream OS = new ObjectOutputStream (FS);
Os.writeobject (Mybox);
Os.close ();

ObjectInputStream in = new ObjectInputStream (New FileInputStream ("Foo.ser"));
Box box = (box) (In.readobject ());
System.out.println (Box.tostring ());
System.out.println (Box.height);
In.close ();
} catch (Exception ex) {
Ex.printstacktrace ();
}
}
}//WriteObject and ReadObject are thread-safe in themselves and are not allowed to be accessed concurrently during transmission. So the object can be passed on one after the other.

Sub-class:

Package wzq.j2se.erializables;

Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;

public class Extendsbox extends box{
int age;

public int getage () {
return age;
}

public void Setage (int.) {
This.age = age;
}

public static void Main (string[] args) {
Extendsbox EB = new Extendsbox ();
Eb.setage (101);
try {
FileOutputStream fs = new FileOutputStream ("abc");
ObjectOutputStream OS = new ObjectOutputStream (FS);
Os.writeobject (EB);
Os.close ();

ObjectInputStream in = new ObjectInputStream (New FileInputStream ("abc"));
Extendsbox box = (Extendsbox) (In.readobject ());
System.out.println (Box.tostring ());
System.out.println (Box.getage ());
In.close ();
} catch (Exception ex) {
Ex.printstacktrace ();
}
}
}

Serialversionuid Effect:
Serialization preserves the uniqueness of the object in order to maintain version compatibility, that is, deserialization while the version is being upgraded.
There are two ways to build:
One is the default 1L, for example: private static final long serialversionuid = 1L;
One is to generate a 64-bit hash field based on the class name, interface name, member method, and property, for example:
Private static final long serialversionuid = XXXXL;

When you implement the serializable interface in a class, if there is no definition serialversionuid,eclipse will provide this hint function to tell you to define. By tapping the warning icon in the class in eclipse, Eclipse automatically gives you two ways to generate it. If you do not want to define it, the settings in eclipse also
You can turn it off, set the following:
Window ==> Preferences ==> Java ==> Compiler ==> error/warnings ==>
Potential programming problems
Change the warning of the serializable class without serialversionuid to ignore.

If you do not consider the compatibility issue, you turn it off, but this function is good, as long as any category implemented serializable this interface, if not joined Serialversionuid,eclipse will give you warning hint, This serialversionuid to make the category serializable backwards compatible.

If your class serialized on the hard drive, but then you change the category field (increase or decrease or rename), when you deserialize, it will appear exception, which will cause incompatibilities.

But when Serialversionuid is the same, it deserialize the different field with the default value of type, which avoids incompatibility issues.

Use of the Java serialization interface serializable

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.