Java object serialization and deserialization Practice

2010-11-13  来源:本站原创  分类:Java  人气:188 

When the two processes during the remote communication, they can send all types of data. No matter what type of data, will be in the form of binary sequences transmitted over the network. The sender need to convert the Java object is a sequence of bytes to send on the network; the receiver is required byte sequence must then return to Java objects.

The Java objects into a sequence of bytes is known as object serialization.

Java byte sequence back to the object is called deserialization of objects.

Object serialization There are two main purposes:

1) The sequence of the object permanently saved to the byte hard drive , usually stored in a file;

2) the object on the network to send the byte sequence.

One. The sequence of the JDK class library API

java.io.ObjectOutputStream on behalf of the object output stream, it's writeObject (Object obj) method can be specified obj parameter object serialization, the resulting sequence of bytes written to a target output stream.

java.io.ObjectInputStream input stream on behalf of the object, its readObject () method from a source input stream as a sequence of bytes, then deserialize them into an object, and return it. ,

Serializable and only realized the object of a class Externalizable interfaces can be serialized. Externalizable interfaces inherited from Serializable interface, the interface of the class to achieve Externalizable controlled entirely by its own sequence of actions, but only implement Serializable interface can be serialized using the default mode.

Object serialization, including the following steps:

1) Create an object output stream, it can target other types of packaging an output stream, such as a file output stream;

2) The object output stream through the writeObject () method to write the object.

The object deserialized as follows:

1) Create an object input stream, it can wrap a stream of other types of source inputs, such as file input stream;

2) the input stream object readObject () method to read objects.

Let us look at a corresponding example of the class as follows:

import java.io. *;
import java.util.Date;

/ **
* Object serialization and deserialization test class.
* @ Author <a href="mailto:[email protected]"> AmigoXie </ a>
* @ Version 1.0
* Creation date: 2007-9-15 - 21:45:48 PM
* /

public class ObjectSaver {
/ **
* @ Param args
* @ Author <a href="mailto:xi[email protected]"> AmigoXie </ a>
* Creation date: 2007-9-15 - 21:45:37 PM
* /

public static void main (String [] args) throws Exception {
ObjectOutputStream out = new ObjectOutputStream
(New FileOutputStream ("D:" "objectFile.obj"));

/ / Serialize object

Customer customer = new Customer ("A honey fruit", 24);
out.writeObject ("Hello!");
out.writeObject (new Date ());
out.writeObject (customer);
out.writeInt (123); / / write the basic types of data out.close ();
/ / Deserialize objects

ObjectInputStream in = new ObjectInputStream
(New FileInputStream ("D:" "objectFile.obj"));

System.out.println ("obj1 =" + (String) in.readObject ());
System.out.println ("obj2 =" + (Date) in.readObject ());
Customer obj3 = (Customer) in.readObject ();
System.out.println ("obj3 =" + obj3);
int obj4 = in.readInt ();
System.out.println ("obj4 =" + obj4);
in.close ();
}
}

class Customer implements Serializable {
private String name;
private int age;
public Customer (String name, int age) {
this.name = name;
this.age = age;
}

public String toString () {
return "name =" + name + ", age =" + age;
}
}

The output is:

obj1 = Hello!

obj2 = Sat Sep 15 22:02:21 CST 2007

obj3 = name = A honey fruit, age = 24

obj4 = 123

Therefore, relatively simple cases, this will not elaborate.

II. Implement the interface Serializable

Serializable interface ObjectOutputStream class can only be serialized objects. By default, ObjectOutputStream by default serialization, this serialization of objects only non-transient instance variables are serialized, serialized objects and not transient instance variables, static variables will not be serialized.

When ObjectOutputStream deserialized by default when the following features:

1) If the memory in the class of the object has not been loaded, so will first load and initialize the class. If the classpath does not exist in the corresponding class files, then throws ClassNotFoundException;

2) During deserialization the class does not call any constructor.

If you want to control the serialization class, serializable class can provide the following forms of writeObject () and readObject () method.

private void writeObject (java.io.ObjectOutputStream out) throws IOException

private void readObject (java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

When a Customer object ObjectOutputStream serialize, if the object has a writeObject () method, it will implement this method, otherwise by default serialization. In the object writeObjectt () method, you can first call the ObjectOutputStream's defaultWriteObject () method, making the object output stream before the implementation of the default serialization. Similarly, deserialization can be drawn from the case, but this is defaultReadObject () method.

Some objects contain sensitive information that should not be open to the public. If by default serialize them, then their sequence data transmitted over the network may be criminals to steal. For such information, you can encrypt them after serialization, deserialization when the decryption is required, and then revert to the original information.

The default serialization will serialize the entire object graph, which requires recursively traverse the object graph. If the object graph is complex, recursive traversal needs to consume a lot of space and time, its internal data structures for the two-way list.

In the application, if the variables are changed to some members of the transient type, will save space and time, improve serialization performance.

III. Implement the interface Externalizable

Externalizable interface inherits from the Serializable interface, if a class implements Externalizable interface, this class will be completely controlled by the sequence of their own behavior. Externalizable interface declares two methods:

public void writeExternal (ObjectOutput out) throws IOException

public void readExternal (ObjectInput in) throws IOException, ClassNotFoundException

The former is responsible for serialization, which is responsible for deserialization operations.

In the interface to achieve the object of a class Externalizable deserialized, it will first call the class constructor with no arguments, which is different from the default mode of anti-sequence. If the class constructor with no arguments to delete, or to access the constructor is set to private, or protected default level, it will throw java.io.InvalidException: no valid constructor exception.

IV. Serializable class compatibility of different versions of the sequence of

Those who implement the interface Serializable class has a serialized version of that static variable identifier:

private static final long serialVersionUID;

SerialVersionUID values is more than Java runtime environment based on the internal details of classes automatically generated. If the source code of the class was revised and re-compile the new class files generated serialVersionUID values may also change.

Class serialVersionUID default value is totally dependent on the implementation Java compilers, for the same class, with a different Java compiler, which may lead to different serialVersionUID, may also be the same. Oh, ah serialVersionUID order to improve the independence and certainty, it is strongly recommended that a sequence shown in the definition of class serialVersionUID, as it gives a clear value. Explicitly defined serialVersionUID has two purposes:

1) In some cases, I hope the class serialization-compatible on different versions, so need to ensure that different versions of the class have the same serialVersionUID;

2) In some cases, do not want to type the sequence of the different versions compatible, so need to ensure that different versions of the class have different serialVersionUID.

相关文章
  • Java object serialization and deserialization Practice 2010-11-13

    When the two processes during the remote communication, they can send all types of data. No matter what type of data, will be in the form of binary sequences transmitted over the network. The sender need to convert the Java object is a sequence of by

  • java object serialization and deserialization 2008-09-29

    What is serialization: Serialization is to an object's state (the amount of each attribute) are saved, and then at the appropriate time to regain. Serialization is divided into two parts: serialization and deserialization. Serialization is the first

  • Java object serialization and deserialization knowledge point summary 2010-07-26

    One or two concepts, what is serialization? What is deserialized? Serialization: the object into a stream of process is called serialization. Deserialization: the process will flow into the object is called deserialization. Second, general-purpose se

  • Java object serialization and deserialization of a JSON 2010-10-22

    1. Dependent libraries jackson-all-1.6.1.jar 2. Code public class Student { private String name; private int age; public Student () { } public Student (String name, int age) { super (); this.name = name; this.age = age; } public String getName () { r

  • Java object serialization and deserialization two XML 2010-10-23

    1. Dependent libraries xstream-1.3.1.jar xpp3_min-1.1.4c.jar 2. Code public class Student { private String name; private int age; public Student () { } public Student (String name, int age) { super (); this.name = name; this.age = age; } public Strin

  • Why Not Use Java Object Serialization? 2010-05-06

    Java comes with its own serialization mechanism, called Java Object Serialization (often referred to simply as "Java Serialization"), that is tightly integrated with the language, so it's natural to ask why this wasn't used in Hadoop. Here's wha

  • On Java object serialization of 5 things you do not know 2010-05-12

    On Java object serialization of 5 things you do not know Serialized data is secure? Not necessarily right. Ted Neward , CEO, ThoughtWorks, ThoughtWorks Ted Neward is a global consulting firm ThoughtWorks consultant, is president of Neward & Associate

  • Java Object Serialization 2010-03-29

    Java Object Serialization

  • [Reprinted] on the Java object serialization of 5 things you do not know 2010-06-16

    Original: http://www.ibm.com/developerworks/cn/java/j-5things1/index.html This article describes five java object serialization of application scenarios, for understanding the java object serialization of the flexible application of useful

  • JAVA series of object serialization and deserialization 2010-09-28

    1 Introduction Object serialization (Serializable) refers to the object into the process sequence of bytes, and deserialization is the object based on a sequence of bytes the process of recovery. Sequence of the general for the following scenario: 1.

  • java basic concept - object serialization and deserialization 2010-07-19

    Serialization (1): readResolve () method and sequence of the CJC (1) mentioned a problem that readResolve method is Gansha it? At that time did not think about, just out there, this break from Diba Search dots order under this problem. Originally thi

  • Object serialization and deserialization 2010-03-29

    When the two processes when conducting remote communication with each other can send various types of data. No matter what type of data, will be in the form of binary sequences transmitted on the network. The sender needs to the Java object is conver

  • Understanding of Java Object Serialization - Serializable interface 2010-03-20

    Overview: When a class implements the Serializable interface (the interface only marker interface does not contain any method definition), indicating that the class can be serialized. The purpose is to serialize an object that implements Serializable

  • Ajax: Java Object Serialization 2009-11-12

    In this paper, we discuss the basics of Ajax development, but will focus on a number of Java Web developers are most concerned about the issue: In order to generate data on the client. Most Java developers have the Model - View - Controller (MVC) mod

  • Java object serialization implementation to use the deep copy 2011-04-24

    clone is the Object class methods, if the object value or all of the properties belong to the basic types, so no problem copying, but the child object if the object contains a reference, then copy the result is two objects reference the same sub-obje

  • Java serialization and deserialization Summary 2010-08-27

    The Java object is converted to byte sequence is called object serialization. Java byte sequence to restore the object is called object deserialization. java serialization mechanism is introduced mainly to support two important technologies: RMI and

  • Object serialization on the Java 5 things you do not know 2010-10-23

    IBM recently sent the mail to find the mail, on the Java 5 things you do not know the series, that came useful to reprint: http://www.ibm.com/developerworks/cn/java/j-5things/?cmp=dw&cpb=dwjav&ct=dwcom&cr=dwcom&ccy=cn Introduction: Java ob

  • java Serializable (serialization) 2009-05-22

    Transfer from: http://westlifesz.javaeye.com/blog/48618 java.io.Serializable problems caused by - what is serialization? Under what circumstances will be serialized class? Serialization is a mechanism used to handle the object stream, the so-called o

  • Object serialization 2010-09-28

    Object serialization is the process of writing a byte stream and read from the byte stream object. The object state into a byte stream, you can use the java.io package in a variety of byte stream classes to save it to file management to another threa

  • Java custom serialization behavior analysis 2011-04-26

    Under normal circumstances, a class that implements a very simple java serialization, only implements Serializable interface, then, after the class is in the process of cross-transmission, jvm java serialization will follow the rules of the default s