Serialization of Java Objects

Source: Internet
Author: User

Serialization of objects

Serialization: Converts a Java object into a sequence of bytes that can be saved on disk or transmitted over a network.

Deserialization: Converts a sequence of bytes into a Java object.

Object serialization Steps
    • The class of the object that needs to be serialized needs to implement the Serializable interface;

    • To create a ObjectOutputStream instance, ObjectOutputStream is a process flow that needs to be built on the basis of other node flows;
// FileInputStream for node flow New ObjectOutputStream (new FileOutputStream ("Object.txt"));

    • Call ObjectOutputStream's WriteObject () method to output the object;
        // to write the person object to the        object.txt file Oos.writeobject (person);

Examples are as follows:

Defines a person class that implements the Serializable interface

classPersonImplementsjava.io.Serializable {PrivateString name; Private intAge ;  PublicPerson (String name,intAge ) {         This. Name =name;  This. Age =Age ; }     Public voidSetName (String name) { This. Name =name;}  PublicString GetName () {returnname;}  Public voidSetage (intAge) { This. Age =Age ;}  Public intGetage () {returnAge ;}}

Creates an instance object of the person class and writes the object to the Object.txt file.

     Public Static void throws IOException {        //  fileinputstream for node stream        new ObjectOutputStream (  New FileOutputStream ("Object.txt"));         New Person ("Sunwukong", +);         // to write the person object to the Object.txt file         oos.writeobject (person);     }

Object deserialization

Deserialization: Converts a sequence of bytes into a Java object.

Object deserialization steps
    • To create a ObjectInputStream instance, ObjectInputStream is a process flow that needs to be built on the basis of other node flows;
New ObjectInputStream (new FileInputStream ("Object.txt"));

    • Call ObjectInputStream's ReadObject () method to read the object in the stream, which returns a Java object of type objects, and if you know the type of the Java object, you can cast the object to its true type;
Person person = (person) ois.readobject ();
Examples are as follows:

Restores the person object stored in the Object.txt file.

     Public Static void throws FileNotFoundException, IOException, classnotfoundexception{        new ObjectInputStream (new FileInputStream ("Object.txt"));         = (person) ois.readobject ();        System.out.println (Newperson.getname ());    // Output Sunwukong        System.out.println (Newperson.getage ());    // Output    

The deserialized object is a completely new object, a re-constructed object, different from the original object.

     Public Static voidMain (string[] args)throwsIOException, ClassNotFoundException {//Serialization ofObjectOutputStream Oos =NewObjectOutputStream (NewFileOutputStream ("Object.txt")); Person Person=NewPerson ("Sunwukong", 500);        Oos.writeobject (person); //deserializationObjectInputStream Ois =NewObjectInputStream (NewFileInputStream ("Object.txt")); Person Newperson=(person) ois.readobject (); //Newperson is a new object, not the same object as PersonSystem.out.println (person = = Newperson);//Output False}

Restricting instance variables for serialization

In some cases, some instance variables of a class are sensitive information and do not want the system to serialize these instance variables.

Or some instance variables cannot be serialized.

By using the Transient keyword before the instance variable, you can specify that the instance variables are ignored in Java serialization.

If the instance variable in the person class is decorated with the transient keyword before age, the variable is ignored when the person instance object is serialized

classPerson {PrivateString name; //Transient modifying the age variable//the variable is ignored when the object is serialized    Private transient intAge ;  PublicPerson (String name,intAge ) {         This. Name =name;  This. Age =Age ; }     Public voidSetName (String name) { This. Name =name;}  PublicString GetName () {returnname;}  Public voidSetage (intAge) { This. Age =Age ;}  Public intGetage () {returnAge ;}}

     Public Static void throws FileNotFoundException, IOException, classnotfoundexception{        new ObjectInputStream (new FileInputStream ("Object.txt"));         = (person) ois.readobject ();        System.out.println (Newperson.getname ());    // Output Sunwukong         // The age variable is not serialized and the resulting deserialized value is the default value        System.out.println (Newperson.getage ());    // output 0    }

When the instance variable is a reference type

The reference type must be serializable, otherwise the class that owns the instance variable is not serializable (unless the instance variable is decorated with transient).

When an object is serialized, the system automatically serializes the object's instance variable, and if an instance variable is referenced to another object, the referenced object is also serialized;

If an instance variable of the referenced object also references another object, the referenced object is also instantiated;

. . . . . . .

This condition is referred to as recursive serialization.

Example:

Defines the teacher class, where an instance variable of the class is student as a reference type person.

classTeacherImplementsjava.io.Serializable {PrivateString name; //student as reference type    PrivatePerson student;  PublicTeacher (String name, person student) { This. Name =name;  This. Student =student; }     Public voidSetName (String name) { This. Name =name;}  PublicString GetName () {returnname;}  Public voidSetstudent (person student) { This. Student =student;}  PublicPerson Getstudent () {returnstudent;}}

Creates an instance object of the teacher class and serializes the object (written to the Object.txt file)

        // Serialization of        New ObjectOutputStream (new FileOutputStream ("Object.txt"));         New Person ("Sunwukong", +);         New Teacher ("Tangseng", person);         // when you write a teacher object to        Object.txt, // The person object pointed to by the reference type variable student in teacher is also written to Object.txt        Oos.writeobject (teacher);

Deserializes the teacher object, or you can get the person object

        New ObjectInputStream (new FileInputStream ("Object.txt"));         = (Teacher) ois.readobject ();        System.out.println (Newteacher.getname ());    // Output Tangseng        Person Newperson = newteacher.getstudent ();        System.out.println (Newperson.getname ());     // output Sunwukong               System.out.println (Newperson.getage ());     // Output

Serialization of multiple objects

When multiple objects are serialized, the Java serialization mechanism uses the following algorithm:

    • All objects saved to disk have a serialized number;
    • When a program attempts to serialize an object, the program first checks to see if the object has been serialized, and the object is serialized only if it has never been serialized;
    • If an object is already serialized, the program will simply output a serialized number instead of re-serializing the object again.

Example:

Create a Person class instance object person;

Create two Teacher class instance objects T1 and T2, and two objects each contain a person;

Writes the instance object T1, T2, person, T1 to the Object.txt file in turn

     Public Static voidMain (string[] args)throwsIOException, ClassNotFoundException {//Serialization ofObjectOutputStream Oos =NewObjectOutputStream (NewFileOutputStream ("Object.txt")); Person Person=NewPerson ("Sunwukong", 500); Teacher T1=NewTeacher ("Tangseng", person); Teacher T2=NewTeacher ("Putizushi", person); //when you write the above objects to Object.txt,oos.writeobject (t1);        Oos.writeobject (T2);        Oos.writeobject (person);        Oos.writeobject (t1); //deserializationObjectInputStream Ois =NewObjectInputStream (NewFileInputStream ("Object.txt")); //read an object in Object.txt in turnTeacher NEWT1 =(Teacher) ois.readobject (); Teacher Newt2=(Teacher) ois.readobject (); Person Newperson=(person) ois.readobject (); Teacher obj=(Teacher) ois.readobject (); System.out.println (Newt1.getstudent ()= = Newt2.getstudent ());//trueSystem.out.println (newt1.getstudent () = = Newperson);//trueSystem.out.println (newt1 = = obj);//true}

Only 3 objects of the above program are serialized: person, T1, T2.

Oos.writeobject (t1);    Serializing T1 with person
Oos.writeobject (T2); The serialized T2,person has been serialized, and the T2 is stored in the person serialization encoding
The person has been serialized, storing the person serialization encoding
oos.writeobject (t1);       The T1 has been serialized, storing the T1 serialization encoding

So, when you remove an object from the Object.txt

Newperson is the same object as the person in Newt1, newt2

Obj is the same object as NEWT1.

Other

Here are a few things to note about object serialization:

The class name of the object, the instance variable are serialized, the method, the class variable (the static decorated member variable), and the transient instance variable are not serialized.

The instance variables of the serialized object should also be serializable, otherwise decorated with the transient keyword.

You must have a class file for the serialized object when deserializing the object.

The deserialized read object must be read in the actual write order.

Serialization of Java 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.