Serializable examples of serialization and deserialization of Java objects

Source: Internet
Author: User
Tags object serialization serialization versions

First, the concept of serialization and deserialization

The process of converting an object to a sequence of bytes is called serialization of objects.
The process of restoring a byte sequence to an object is called deserialization of an object.
There are two main uses for serialization of objects:
1 The object's byte sequence is permanently saved to the hard disk, usually stored in a file;
2 transfer the byte sequence of the object on the network.

In many applications, some objects need to be serialized so that they leave the memory space and stay in the physical hard drive for long-term preservation. For example, the most common is the Web server session object, when there are 100,000 users concurrent access, there may be 100,000 session objects, memory may be too much, so the Web container will be some seesion first serialized to the hard disk, and so on, Then restore the objects saved in the hard disk to memory.

When two processes are communicating remotely, they can send different types of data. Regardless of the type of data, it is transmitted over the network in the form of a binary sequence. The sender needs to convert the Java object into a byte sequence to be routed over the network, and the receiver needs to revert the byte sequence back to the Java object.

Ii. serialization APIs in JDK class libraries

Java.io.ObjectOutputStream represents an object output stream whose WriteObject (object obj) method serializes the Obj object specified by the parameter and writes the resulting byte sequence to a target output stream.
Java.io.ObjectInputStream represents an object input stream whose ReadObject () method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns them.
Only objects of classes that implement the serializable and Externalizable interfaces can be serialized. The Externalizable interface inherits from the serializable interface, and the class that implements the Externalizable interface controls the serialization behavior entirely by itself, and the class that implements only the serializable interface can use the default serialization method.
Object serialization consists of the following steps:
1 Create an object output stream that can wrap a different type of target output stream, such as a file output stream;
2 The object is written through the WriteObject () method of the object output stream.

The steps to deserialize an object are as follows:
1 Create an object input stream that can wrap a different type of source input stream, such as a file input stream;
2 The object is read by the ReadObject () method of the object input stream.

Examples of object serialization and deserialization:

Define a person class to implement the Serializable interface

1 Import java.io.Serializable;
2
3/**
4 * <p>ClassName:Person<p>
5 * <p>description: Test object serialization and deserialization <p>
6 * @author XUDP
7 * @version 1.0 V
8 * @createTime 2014-6-9 02:33:25
9 */
Ten public class person implements Serializable {
11
12/**
13 * Serialization ID
14 */
Private static final long serialversionuid = -5809782578272943999l;
-Private int age;
The private String name;
a private String sex;
19
public int getage () {
return to age;
22}
23
Public String GetName () {
return name;
26}
27
Public String Getsex () {
return sex;
30}
31
setage void (int age) {
This.age = age;
34}
35
The public void SetName (String name) {
Panax this.name = name;
38}
39
public void Setsex (String sex) {
This.sex = sex;
42}
43}
Serialization and deserialization of a person class object

1 Import java.io.File;
2 Import Java.io.FileInputStream;
3 Import java.io.FileNotFoundException;
4 Import Java.io.FileOutputStream;
5 Import java.io.IOException;
6 Import Java.io.ObjectInputStream;
7 Import Java.io.ObjectOutputStream;
8 Import Java.text.MessageFormat;
9
10/**
* <p>ClassName:TestObjSerializeAndDeserialize<p>
* <p>description: Serialization and deserialization of test objects <p>
* @author XUDP
* @version 1.0 V
* @createTime 2014-6-9 03:17:25
16 */
The public class Testobjserializeanddeserialize {
18
public static void Main (string[] args) throws Exception {
Serializeperson ()//serialization of a Person object
Person P = Deserializeperson ();//Reverse Sequence Perons object
System.out.println (Messageformat.format ("name={0},age={1},sex={2}"),
P.getname (), P.getage (), P.getsex ());
24}
25
26/**
* Methodname:serializeperson
* Description: Serializing a Person object
* @author XUDP
* @throws FileNotFoundException
* @throws IOException
32 */
The private static void Serializeperson () throws FileNotFoundException,
IOException {
person is = new person ();
Person.setname ("GaCl");
Panax Notoginseng Person.setage (25);
Person.setsex ("male");
The ObjectOutputStream object output stream, which stores the person object to the Person.txt file in e disk, and completes the serialization of the person object
ObjectOutputStream oo = new ObjectOutputStream (New FileOutputStream (
The new File ("E:/person.txt"));
Oo.writeobject (person);
System.out.println ("The Person object serialized successfully!") ");
Oo.close ();
45}
46
47/**
Methodname:deserializeperson *
Description: Reverse Sequence Perons Object
* @author XUDP
Wuyi @return
* @throws Exception
* @throws IOException
54 */
The private static person Deserializeperson () throws Exception, IOException {
ObjectInputStream ois = new ObjectInputStream (New FileInputStream (
New File ("E:/person.txt"));
Person of person = (person) ois.readobject ();
System.out.println ("The Person object deserialized successfully!") ");
return to person;
61}
62
63}
The results of the code run are as follows:

The serialized person succeeded in generating a Person.txt file on E disk, while the deserialized person was reading the E-disk Person.txt became a person object

Third, the role of Serialversionuid

S e r i a l V e R S i o n U i D: It is a serialized version number in literal sense, and a class that implements the Serializable interface has a static variable that represents the serialized version identifier

1 private static final long Serialversionuid
Classes that implement the Serializable interface if no serialversionuid are added to the class, the following warning prompts appear

Click on the mouse will pop up to generate Serialversionuid dialog box, as shown in the following figure:

There are two ways to generate SERIALVERSIONUID:

The serialversionuid generated in this manner is 1L, for example:

1 private static final long serialversionuid = 1L;
The serialversionuid generated in this way are generated based on the class name, interface name, method, and property, for example:

1 private static final long serialversionuid = 4603642343377807741L;
The warning will not appear after you add it, as follows:

So many, then Serialversionuid (serialized version number) What is the use of it, we use the following example to illustrate the role of Serialversionuid, look at the following code:

1 Import java.io.File;
2 Import Java.io.FileInputStream;
3 Import java.io.FileNotFoundException;
4 Import Java.io.FileOutputStream;
5 Import java.io.IOException;
6 Import Java.io.ObjectInputStream;
7 Import Java.io.ObjectOutputStream;
8 Import java.io.Serializable;
9
Ten public class Testserialversionuid {
11
The public static void main (string[] args) throws Exception {
Serializecustomer ();//serialization of the Customer object
Customer customer = Deserializecustomer ()//Reverse Sequence Customer object
SYSTEM.OUT.PRINTLN (customer);
16}
17
18/**
* Methodname:serializecustomer
Description: Serializing a Customer object
* @author XUDP
* @throws FileNotFoundException
* @throws IOException
24 */
The private static void Serializecustomer () throws FileNotFoundException,
Num IOException {
Customer customer = new Customer ("GaCl", 25);
//ObjectOutputStream Object output stream
ObjectOutputStream oo = new ObjectOutputStream (New FileOutputStream (
New File ("E:/customer.txt"));
Oo.writeobject (customer);
System.out.println ("Customer object Serialization success!") ");
Oo.close ();
34}
35
36/**
Notoginseng * Methodname:deserializecustomer
* Description: Anti-Sequence Customer object
XUDP @author
* @return
@throws Exception
* @throws IOException
43 */
The private static Customer Deserializecustomer () throws Exception, IOException {
ObjectInputStream ois = new ObjectInputStream (New FileInputStream (
The new File ("E:/customer.txt"));
Customer customer = (customer) ois.readobject ();
System.out.println ("Customer object deserialization succeeded!") ");
return to Customer;
50}
51}
52
53/**
* <p>ClassName:Customer<p>
The * <p>description:customer implements the Serializable interface, which can be serialized <p>
* @author XUDP
* @version 1.0 V
* @createTime 2014-6-9 04:20:17
59 */
Class Customer implements Serializable {
Serialversionuid is not defined in the//customer class
The private String name;
the private int age;
64
Public Customer (String name, int age) {
THIS.name = name;
This.age = age;
68}
69
70/*
* @MethodName toString
The ToString () method of the @Description override object class
@author XUDP
* @return String
* @see java.lang.object#tostring ()
76 */
@Override
The public String toString () {
"Name=" + name + ", age=" + age;
80}
81}
Run Result:

Both serialization and deserialization succeeded.

Let's revise the customer class to add one more sex attribute, as follows:

1 class Customer implements Serializable {
No Serialversionuid defined in the//customer Class 2
3 private String name;
4 private int age;
5
6//The newly added sex property
7 Private String sex;
8
9 Public Customer (String name, int age) {
Ten this.name = name;
One this.age = age;
12}
13
Public Customer (String name, int age,string sex) {
THIS.name = name;
This.age = age;
This.sex = sex;
18}
19
20/*
* @MethodName toString
* @Description rewrite the ToString () method of the object class
* @author XUDP
* @return String
* @see java.lang.object#tostring ()
26 */
@Override
Public String toString () {
"Name=" + name + ", age=" + age;
30}
31}
Then the deserialization operation is performed, and the following exception information is thrown:

1 Exception in thread "main" java.io.InvalidClassException:Customer;
2 Local class Incompatible:
3 stream Classdesc Serialversionuid =-88175599799432325,
4 Local Class Serialversionuid =-5182532647273106745
This means that the class in the file stream and class in Classpath, which is the modified class, is incompatible, is in security consideration, the program throws an error, and refuses to load. So what if we really need to add a field or method after serialization? What should I do? That is to specify the serialversionuid yourself. In the Testserialversionuid example, the Serialversionuid of the customer class is not specified, so the Java compiler will automatically give this Class A digest algorithm, similar to the fingerprint algorithm, as long as the file more than one space, The resulting UID will be completely different, and it can be guaranteed that the number is unique in so many classes. So, after adding a field, the compiler generates a UID for us because it does not explicitly specify Serialversionuid, which is certainly not the same as the one previously saved in the file, so there are 2 errors that are inconsistent with the serialized version number. Therefore, as long as we specify the Serialversionuid, we can add a field after serialization, or method, without affecting the later restore, the restored object can be used, but also a lot of methods or properties can be used.

The following continues to modify the customer class, assigning a serialversionuid to the customer, with the modified code as follows:

1 class Customer implements Serializable {
2/**
3 * SERIALVERSIONUID (serialized version number) defined in the Customer class
4 */
5 private static final long serialversionuid = -5182532647273106745l;
6 private String name;
7 private int age;
8
9//The newly added sex property
//private String sex;
11
Public Customer (String name, int age) {
THIS.name = name;
This.age = age;
15}
16
/*public Customer (String name, int age,string sex) {
THIS.name = name;
This.age = age;
This.sex = sex;
21}*/
22
23/*
* @MethodName toString
* @Description rewrite the ToString () method of the object class
* @author XUDP
* @return String
* @see java.lang.object#tostring ()
29 */
@Override
To public String toString () {
"Name=" + name + ", age=" + age;
33}
34}
Re-perform the serialization operation, serialize the customer object to the Customer.txt file store on the local hard disk, and then modify the customer class, add the Sex property, and modify the customer Class code as follows:

1 class Customer implements Serializable {
2/**
3 * SERIALVERSIONUID (serialized version number) defined in the Customer class
4 */
5 private static final long serialversionuid = -5182532647273106745l;
6 private String name;
7 private int age;
8
9//The newly added sex property
Ten private String sex;
11
Public Customer (String name, int age) {
THIS.name = name;
This.age = age;
15}
16
Public Customer (String name, int age,string sex) {
THIS.name = name;
This.age = age;
This.sex = sex;
21}
22
23/*
* @MethodName toString
* @Description rewrite the ToString () method of the object class
* @author XUDP
* @return String
* @see java.lang.object#tostring ()
29 */
@Override
To public String toString () {
"Name=" + name + ", age=" + age;
33}
34}
To perform the deserialization operation, this time the reverse sequence is successful, as follows:

Iv. Value of Serialversionuid

The Serialversionuid value is generated automatically by the Java Runtime Environment based on the internal details of the class. If you modify the source code for the class, and then recompile, the value of the serialversionuid of the newly generated class file may change.
The default value of a class's serialversionuid is entirely dependent on the implementation of the Java compiler, and for the same class, compiling with a different Java compiler may lead to different serialversionuid, and possibly the same. In order to improve the independence and certainty of serialversionuid, it is strongly recommended that the definition shown in a serializable class be serialversionuid, giving it a definite value.

There are two uses for explicitly defining SERIALVERSIONUID:
1, in some cases, you want different versions of the class to be compatible with serialization, so you need to ensure that different versions of the class have the same serialversionuid;
2, in some cases, you do not want different versions of the class to be compatible with serialization, so you need to ensure that different versions of the class have different serialversionuid.

Related Article

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.