Java object serialization and deserialization, java object serialization

Source: Internet
Author: User

Java object serialization and deserialization, java object serialization

Object serialization aims to save an object on a disk or transmit it over a network. The implementation mechanism is to allow the object to be converted into a platform-independent binary stream.

The serialization mechanism of objects in java is to convert objects into byte sequences. These byte sequences allow Java objects to be detached from programs and stored on disks or transmitted between networks.

Object serialization writes a Java object to the IO stream. In contrast, deserialization restores a Java object from the IO stream.

Implement serialization

To serialize a java object, the class of the object must be serializable. To make the class serializable, the class must inherit the following two interfaces:

  • Serializable
  • Externalizable
Serializable serialization

The implementation of the Serializable interface is very simple, as long as java can implement the Serializable interface, no need to implement any method.

Once a class implements the Serializable interface, its objects can be serialized. You can use ObjectOutputStream to serialize object of the implementation class. The implementation steps are as follows:

  • Create an ObjectOutputStream object;
  • Call the writeObject method of ObjectOutputStream to output the object.

The following is an instance:

Package com. zhyea. test; import java. io. fileOutputStream; import java. io. IOException; import java. io. objectOutputStream; import java. io. serializable;/*** serialization test class ** @ author robin * @ date July 15, December 18, 2014 */public class SerialTest {public static void main (String [] args) {ObjectOutputStream oos = null; try {oos = new ObjectOutputStream (new FileOutputStream ("D: \ object.txt"); Person robin = new Person ("rob In ", 29); oos. writeObject (robin);} catch (IOException e) {e. printStackTrace () ;} finally {if (null! = Oos) {try {oos. close ();} catch (IOException e) {e. printStackTrace ();}}}}} /*** serialization test object ** @ author robin * @ date July 22, December 18, 2014 */class Person implements Serializable {private static final long serialVersionUID =-6412852654889352693L; /*** name */private String name;/*** age */private int age; public Person () {} public Person (String name, int age) {this. name = name; this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}}

The current Code stores a personas object in the corresponding object object.txt. The runtime program generates an object.txt file on the D Drive. The following is the file content:

Package com. zhyea. test; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; import java. io. objectInputStream; import java. io. objectOutputStream; import java. io. serializable;/*** serialization test class ** @ author robin * @ date December 18, 2014 */public class SerialTest {public static void main (String [] args) {Person robin = new Person ("robin", 29); String savePath = "D: \ object.txt "; SerialTest test = new SerialTest (); try {test. serialize (robin, savePath); Person person = (Person) test. deSerialize (savePath); System. out. println ("Name:" + person. getName () + "Age:" + person. getAge ();} catch (IOException e) {e. printStackTrace ();} catch (ClassNotFoundException e) {e. printStackTrace () ;}}/*** implement serialization ** @ param obj * object to be serialized and saved * @ param path * save address * @ throws IOException * /Public void serialize (Object obj, String path) throws IOException {ObjectOutputStream oos = null; try {oos = new ObjectOutputStream (new FileOutputStream (path); oos. writeObject (obj);} finally {if (null! = Oos) oos. close ();}} /*** deSerialize the retrieved Object ** @ param path * location of the serialized Object * @ return * @ throws IOException * @ throws ClassNotFoundException */public Object deSerialize (String path) throws IOException, ClassNotFoundException {ObjectInputStream ois = null; try {ois = new ObjectInputStream (new FileInputStream (path); return ois. readObject ();} finally {if (null! = Ois) ois. close () ;}}/*** serialization test object ** @ author robin * @ date December 18, 2014 */class Person implements Serializable {private static final long serialVersionUID =-6412852654889352693L; /*** name */private String name;/*** age */private int age; public Person () {} public Person (String name, int age) {this. name = name; this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}}

Pay attention to the following points for Object serialization and deserialization:

  • Deserialization does not require object initialization through the constructor;
  • If multiple objects are written to the file using the serialization mechanism, the order of retrieval and writing must be consistent;
  • When Java serializes class objects, if the class has an object reference (and the value is not null), it will also serialize the referenced objects of the class.
Use transient

In some special scenarios, such as the bank account object, the deposit amount is not serialized for confidentiality reasons. Or some reference type members of the class cannot be serialized. In this case, you can use the transient keyword to modify the member variables that do not want to be or cannot be serialized.

Continue to adjust our code for Demonstration:

Package com. zhyea. test; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; import java. io. objectInputStream; import java. io. objectOutputStream; import java. io. serializable;/*** serialization test class ** @ author robin * @ date December 18, 2014 */public class SerialTest {public static void main (String [] args) {Person robin = new Person ("robin", 29); School school = new School ("XX School"); Teacher tRobin = new Teacher (robin); tRobin. setSchool (school); tRobin. setSalary (12.0); String savePath = "D: \ object.txt"; SerialTest test = new SerialTest (); try {test. serialize (savePath, tRobin); Teacher t = (Teacher) test. deSerialize (savePath); System. out. println ("Name:" + t. getPerson (). getName () + "Salary:" + t. getSalary ();} catch (IOException e) {e. printStackTrace ();} catch (ClassNotFoundException e) {e. printStackTrace ();}} /*** implement serialization ** @ param obj * object to be serialized and saved * @ param path * save address * @ throws IOException */public void serialize (String path, object... obj) throws IOException {....} /*** deSerialize the retrieved Object ** @ param path * location of the serialized Object * @ return * @ throws IOException * @ throws ClassNotFoundException */public Object deSerialize (String path) throws IOException, ClassNotFoundException {...}} /*** Teacher class * @ author robin * @ date July 22, December 18, 2014 */class Teacher implements Serializable {private static final long serialVersionUID =-8751853088437904443L; private Person; private transient School; private transient double salary; public Teacher (Person person) {this. person = person;}/* Skip get and set. Please add */}/*** School class by yourself, not serializable ** @ author robin * @ date December 18, 2014 */class School {private String name; public School (String name) {this. name = name;}/* Skip get and set. Please add the */}/*** Person class by yourself, serializable ** @ author robin * @ date December 18, 2014 */class Person implements Serializable {....}

When the school Member of the Teacher class is not added with the transient identifier, if the school value is not null, NotSerializableException is reported. The exception information is as follows:
Package com. zhyea. test; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; import java. io. objectInputStream; import java. io. objectOutputStream; import java. io. serializable; import com. sun. xml. internal. ws. encoding. soap. deserializationException;/*** serialization test class ** @ author robin * @ date February */public class SerialTest {public static void main (String [] args) {Person robin = new Person ("robin", 29); String savePath = "D: \ object.txt"; SerialTest test = new SerialTest (); try {test. serialize (savePath, robin); Person person = (Person) test. deSerialize (savePath); System. out. println ("Name:" + person. getName () + "Age:" + person. getAge ();} catch (IOException e) {e. printStackTrace ();} catch (ClassNotFoundException e) {e. printStackTrace ();}} /*** implement serialization ** @ param obj * object to be serialized and saved * @ param path * save address * @ throws IOException */public void serialize (String path, person... obj) throws IOException {ObjectOutputStream oos = null ;...} /*** deSerialize the retrieved Object ** @ param path * location of the serialized Object * @ return * @ throws IOException * @ throws ClassNotFoundException */public Object deSerialize (String path) throws IOException, ClassNotFoundException {...}} /*** Person class, Serializable ** @ author robin * @ date July 22, December 18, 2014 */class Person implements Serializable {private static final long serialVersionUID =-6412852654889352693L; /*** name */private String name;/*** age */private int age; public Person () {} public Person (String name, int age) {this. name = name; this. age = age;}/* Skip get and set. Implement */private void writeObject (ObjectOutputStream out) throws IOException {out. writeObject (name); out. writeInt (age + 1); System. out. println ("my write");} private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException {this. name = "zhangsan"; this. age = 30; System. out. println ("my read ");}}

The output result is as follows:

Original situation of readObjectNoData pojo public class Person implements Serializable {private int age; public Person () {}// setter getter ...} serialize Person p = new Person (); p. setAge (10); ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("c:/person. ser "); oos. writeObject (p); oos. flush (); oos. close (); after the class structure changes, the serialized data remains unchanged. pojo Animal implements Serializable explicitly writes readObjectNoData public class Animal implements Serializable {private String name; public Animal () {} // setter getter... private void readObjectNoData () {this. name = "zhangsan" ;}} Person extends Animal public class Person extends Animal implements Serializable {private int age; public Person () {}// setter getter ...} deserialization ObjectInputStream ois = new ObjectInputStream (new FileInputStream ("c:/person. ser "); Person sp = (Person) ois. readObject (); System. out. println (sp. getName (); readObject calls readObjectNoData

ReadObjectNoData seems to me as an exception handling mechanism to return the correct value when the serialized stream is incomplete.

WriteReplace and readResolve

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.