Knowledge points for serializing and deserializing objects in Java---IO learning notes (iv)

Source: Internet
Author: User
Tags object serialization

serialization of objects, deserialization
Serialization of the object:
is to convert the object into a byte sequence
Deserialization of the object:
Converts a byte sequence into an object

serializing a stream, deserializing a stream
Serialization Stream (ObjectOutputStream), which is a byte filter flow, Main method: WriteObject ()
Deserialization Stream (ObjectInputStream), Main method: ReadObject ()

serialization Interface (Serializable)
Object must implement a serialization interface for serialization, or an exception will occur
This interface, there is no method, just a standard.

Basic object Serialization Operations:
Student Entity classes:

 PackageCom.test.ObjectInputStream;Importjava.io.Serializable; Public  class Student implements Serializable{    PrivateString name;Private intAgePrivateString sex; Public Student(String name,intAge, String Sex) {Super(); This. name = name; This. Age = Age; This. sex = sex; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; } PublicStringGetsex() {returnSex } Public void Setsex(String Sex) { This. sex = sex; }@Override     PublicStringtoString() {return "Student [name="+ name +", age="+ Age +", sex="+ Sex +"]"; }}

Object serialization and deserialization operations class:

 PackageCom.test.ObjectInputStream;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream; Public  class objectinputstreamtest {     Public Static void Main(string[] args)throwsIOException {String filename ="c:\\users\\administrator\\desktop\\javaio\\ test objectoutputstream file. txt";////1. Serialization of Objects//ObjectOutputStream Oos = new ObjectOutputStream (new FileOutputStream (filename));//Student stu = new Student ("Small grey ash", 22, "male");//Oos.writeobject (STU);//Oos.flush ();//Oos.close ();        //2. Deserialization of ObjectsObjectInputStream Ois =NewObjectInputStream (NewFileInputStream (filename));Try{Student stu1 = (Student) ois.readobject ();        System.out.println (STU1); }Catch(ClassNotFoundException e)        {E.printstacktrace ();    } ois.close (); }}

Results:

The above example is: first through the serialization of the object to the object serialization of the contents of the file, and then in the object's deserialization from the file and then the object serialized content read out.

Note: The place to use serialization: when the network transmits object data

Use of the Transient keyword:

When a transient adornment is added before the name attribute in the student entity class, the property is not serialized by default by the JVM, or it can be serialized by itself.

Then the result of the above program is:

Actually view the source code of ArrayList class:
The ArrayList class implements the serialization interface:

The array of element data in ArrayList uses the transient keyword decoration:

    /**     * The array buffer into which the elements of the ArrayList are stored.     * The capacity of the ArrayList is the length of this array buffer. Any     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA     * will be expanded to DEFAULT_CAPACITY when the first element is added.     */    transient// non-private to simplify nested class access

The ReadObject () method in ArrayList

 /** * Reconstitute the <tt>ArrayList</tt> instance from a stream (which is, * deserialize it). */    Private void ReadObject(Java.io.ObjectInputStream s)throwsJava.io.IOException, classnotfoundexception {elementdata = Empty_elementdata;//Read in size, and any hidden stuffS.defaultreadobject ();//Read in capacityS.readint ();//Ignored        if(Size >0) {//Be-like clone (), allocate array based upon size not capacityEnsurecapacityinternal (size); Object[] A = Elementdata;//Read in all elements in the proper order.             for(intI=0; i<size;            i++) {A[i] = S.readobject (); }        }    }

The Writeobjct () method in ArrayList:

 /** * Save The state of the <tt>ArrayList</tt> instance to a stream (that's, serialize it). * * @serialData The length of the array backing the <tt>ArrayList</tt> * Instan  Ce is emitted (int.), followed by all of their elements * (each a <tt>Object</tt>) in the proper     Order. */    Private void writeobject(Java.io.ObjectOutputStream s)throwsjava.io.ioexception{//Write out element count, and any hidden stuff        intExpectedmodcount = Modcount; S.defaultwriteobject ();//Write out size as capacity-behavioural compatibility with clone ()S.writeint (size);//Write out all elements in the proper order.         for(intI=0; i<size;        i++) {s.writeobject (elementdata[i]); }if(Modcount! = expectedmodcount) {Throw NewConcurrentmodificationexception (); }    }

Why is an array of element data in the ArrayList class decorated with the transient keyword?
Reason:
Rather than not wanting to be serialized, I have implemented my own serialization and deserialization operations to improve performance because ArrayList cannot determine the number of data elements, so the root cause of the transient keyword modification is to serialize the valid elements in the array, and the invalid elements will not be serialized. , which can improve performance.

Serialization of child classes and the invocation of a parent class constructor

Two questions:
(1) A class implements a serialized interface, and its subclasses can be serialized.
(2) When a subclass object is deserialized, the constructor of its parent class is explicitly called if its parent does not implement the serialization interface.

Package Com.test.objectinputstream;import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.objectinputstream;import Java.io.objectoutputstream;import java.io.Serializable; Public  class objectserialtest {     Public Staticvoid Main (string[] args) {String filename ="c:\\users\\administrator\\desktop\\javaio\\ test serialization calls the problem file. txt";Try{//writeobject (filename);ReadObject (filename); }Catch(Exceptione) {e.printstacktrace (); }    } Public Staticvoid WriteObject (String filename) throwsException{ObjectOutputStream Oos =NewObjectOutputStream (NewFileOutputStream (filename)); Person3 Person3 =NewPerson3 ();        Oos.writeobject (Person3);        Oos.flush ();    Oos.close (); } Public Staticvoid ReadObject (String filename) throwsException{ObjectInputStream Ois =NewObjectInputStream (NewFileInputStream (filename));        Person1 person = (Person1) ois.readobject ();        SYSTEM.OUT.PRINTLN (person);    Ois.close (); }} class Person1 {     PublicPerson1 () {System.out.println ("Person1"); }} class Person2 extends Person1 implements Serializable {      PublicPerson2 () {System.out.println ("Person2"); }} class Person3 extends Person2 {     PublicPerson3 () {System.out.println ("Person3"); }}

Results:

The above code, when changed to Person3, does not implement the serialization interface for the two parent classes, but only when the Person3 implements the serialization interface, the deserialization produces such a result (),

, so we can know the conclusion of the second question through the above example.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Knowledge points for serializing and deserializing objects in Java---IO learning notes (iv)

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.