Serialization of objects

Source: Internet
Author: User
Tags object serialization

First, the concept and purpose of serialization

1. What is serialization

The life of an object is usually terminated with the termination of the program that generated the object. Sometimes, you might need to save the state of an object and restore the object when you need it. We put the object's ability to record its state so that it can regenerate in the future. Known as the persistence of the object (persistence). The object records itself by writing a value describing its state, which is called the serialization of the object (serialization). The main task of serialization is to write out the value of the object instance variable. If the throughput is a reference to another object, the referenced object is also serialized. This process is recursive, and serialization may involve the single-line of a complex tree structure, including the original object, object objects, objects of objects, and so on. The hierarchical structure of object ownership is called a graph (graph).

2. Purpose of serialization

The goal of a single-line Java object is to provide a set of attributes for the Java runtime, as follows:

1) Try to keep the serialization of the object as simple as possible, but provide a way to expand or customize it according to the requirements of the developer.

2) The serialization mechanism should strictly abide by the Java object model. The serialization state of an object should have all the information about the security characteristics of the species.

3) The serialization mechanism of the object should support Java object persistence.

4) The serialization mechanism of an object should have sufficient scalability to support the object's remote method invocation (RMI).

5) object serialization should allow the object to define its own format, which is its own data flow representation, which can be done by an external interface.

Second, serialization method
Starting with JDK1.1, the Java language provides an object serialization mechanism in which the interface serialization is used as a tool for implementing the serialization of objects, and only objects that implement the serialization class can be serialized.

There is no method in the serializable interface. When a class declares that it is implementing the Serializable interface, it simply indicates that the class participates in the serialization protocol and does not need to implement any special methods. Here we show you how to serialize an object by using an example.

1. Defining a Serializable Object

A class that must implement the serializable interface if it is to enable its objects to be serialized. We define a class student as follows:

Import java.io.serializable;  
 
public class Student implements Serializable {   br> 
    int id;//number   
 
    String name;//name    
 
    int age;//age   
 
    String Department; Department   
 
    public Student (int ID, string name, Int. age, String department) {&NBSP ; 
 
        this.id = id;  
 
         this.name = name;  
 
         this.age = age;  
 
        this.department = department;  
 
   }  
 

2. Construct an input/output stream for an object

To serialize an object, it must be associated with a certain object output/input stream, save the state of the object through the object output stream, and restore the object state through the object input stream.

In the java.io package, ObjectInputStream and ObjectOutputStream are provided to extend the data flow capabilities to read-write objects. In ObjectInputStream, an object can be read directly using the ReadObject () method, and the object can be saved directly to the output stream using the WriteObject () method in ObjectOutputStream.

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

public class Objectser {

public static void Main (String args[]) throws IOException,
classnotfoundexception {

Student stu = new Student (981036, "liuming", "CSD");

FileOutputStream fo = new FileOutputStream ("Data.ser");

ObjectOutputStream so = new ObjectOutputStream (FO);

try {

So.writeobject (Stu);

So.close ();

} catch (IOException e) {
System.out.println (e);
}

Stu = null;

FileInputStream fi = new FileInputStream ("Data.ser");

ObjectInputStream si = new ObjectInputStream (FI);

try {

Stu = (Student) si.readobject ();

Si.close ();

} catch (IOException e)

{
System.out.println (e);
}

System.out.println ("Student Info:");

System.out.println ("ID:" + stu.id);

System.out.println ("Name:" + stu.name);

System.out.println ("Age:" + stu.age);

System.out.println ("DEP:" + stu.department);

}

}
The results of the operation are as follows:

Student Info:

id:981036

Name:liuming

Age:18

Dep:csd

In this example, we first define a class student, implement the Serializable interface, and then save the student object to the file Data.ser through the WriteObject () method of the object output stream. After that, the saved student object is read from the file Data.ser through the Readobjcet () method of the home input stream. As you can see from the running results, the state of the object can be saved and restored correctly by serialization mechanism.

Iii. Considerations for serialization
1. Serialization of the elements that can be saved

Serialization can only hold non-static member arguments of an object, cannot save any member methods and static member variables, and serialization saves only the value of the variable, and no modifier for the variable can be saved.

2.transient keywords

For certain types of objects whose state is instantaneous, such an object cannot save its state. For example, a thread object or a FileInputStream object, we must use the Transient keyword for these fields, otherwise the compiler will report.

In addition, serialization may involve storing objects on disk or developing data on the network, which can create security issues. Because the data is outside the Java Runtime Environment, it is not under the control of Java security. For those fields that require secrecy, they should not be stored on permanent media, or should not be saved simply and without processing, in order to ensure security. You should add the Transient keyword before these fields.

The following is an explanation of the transient keyword in the Java specification:
The transient marker is isn't fully specified by the Java Language specification it is used In object serialization to mark member variables this should not being serialized.

Here is an example of a transient application:
/logginginfo.java
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import Java.util.Date;
public class LoggingInfo implements Java.io.Serializable {
Private static final long serialversionuid = 1L;
Private date Loggingdate = new Date ();
Private String uid;
private transient String pwd;
LoggingInfo (string user, string password) {
UID = user;
PWD = password;
}
Public String toString () {
String password = null;
if (pwd = = null) {
Password = "Not SET";
} else {
Password = pwd;
}
Return "Logon info: \ n" + "User:" + uid + "\ n Logging Date:"
+ loggingdate.tostring () + "\ n Password:" + password;
}
public static void Main (string[] args) {
LoggingInfo loginfo = new LoggingInfo ("MIKE", "mechanics");
System.out.println (Loginfo.tostring ());
try {
ObjectOutputStream o = new ObjectOutputStream (New FileOutputStream (
"Loginfo.out"));
O.writeobject (Loginfo);
O.close ();
} catch (Exception e) {//deal with Exception
}
To read the object back, we can write
try {
ObjectInputStream in = new ObjectInputStream (New FileInputStream (
"Loginfo.out"));
LoggingInfo logInfo1 = (logginginfo) in.readobject ();
System.out.println (Loginfo1.tostring ());
} catch (Exception e) {//deal with Exception
}
}
}

Serialization of objects

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.