Serialization of objects

Source: Internet
Author: User
Tags object serialization

Object serialization is a way to turn an object into a binary data stream.

In order for a class to be serialized, the Java.io.Serializable interface must be implemented. Although there is no method in this interface, it is just like the previous cloneable interface. Once this interface is implemented, it indicates that the class has the ability to be serialized.

Let's first implement a class with serialization capabilities:

"Example 1"

Import java.io.*;/** * Implementing a class with serialization capability */Publicclass serializabledemo implements serializable{public serializabledemo () {} public SerializableDemo ( String name, int age) {this.name=name; this.age=age;}  @Override public String  ToString () {return  "name:" +name+private String name; private int age;}        

This class has the ability to serialize, and before continuing to serialize, the two classes of ObjectInputStream and ObjectOutputStream

Let's give a objectoutputstream example:

"Example 2"

Import java.io.Serializable;Import Java.io.File;Import Java.io.FileOutputStream;Import java.io.IOException;Import Java.io.ObjectOutputStream;/** * Implementing a class with serialization capability */PublicClassPersonImplementsserializable{PublicPerson () {}PublicPerson (String name,int age) {THIS.name = name;This.age = age; }@OverridePublic StringToString () {Return"Name:" + name +"Age:" + ages; }private String name;Privateint age;} /** * Demo ObjectOutputStream * */public class objectoutputstreamdemo{public  static void  Main (string[] args) throws ioexception{File File = new file ("D:" + File.separator + "Hello.txt"); ObjectOutputStream Oos = new ObjectOutputStream (new FileOutputStream (file)); Oos.writeobject (New Person ("Rollen") ; Oos.close ();}}            

"Run Results":

When we look at the resulting hello.txt, see is garbled, hehe. Because it is a binary file.

Although we cannot view the contents directly, we can use the ObjectInputStream class to view:

"Example 3"

Import Java.io.File;import java.io.FileInputStream; import java.io.ObjectInputStream; /** * objectinputstream demonstration */public  class objectinputstreamdemo{ Public static void main (String[] args) throws exception{File File = new file (" D: "+ File.separator + " Hello.txt "); ObjectInputStream input = new objectinputstream (new FileInputStream (file)); Object obj = Input.readobject (); Input.close (); System.out.println (obj); }} 

"Run Results":

Name: Rollen Age: 20

What exactly is serialized?

In fact, only attributes are serialized.

    • Externalizable interface

The properties of the object of the class declared by the serializable interface will be serialized, but if you want to customize the serialized content, you need to implement the Externalizable interface.

When a class is going to use the Externalizable interface, there must be a parameterless constructor in the class, and if not, an exception is generated when constructing it, because the parameterless constructor is called by default when deserializing the session.

Now let's demonstrate the serialization and deserialization sessions:

"Example 4"

Package IO;Import java.io.Externalizable;Import Java.io.File;Import Java.io.FileInputStream;Import Java.io.FileOutputStream;Import java.io.IOException;Import Java.io.ObjectInput;Import Java.io.ObjectInputStream;Import Java.io.ObjectOutput;Import Java.io.ObjectOutputStream;/** * Serialization and deserialization operations */PublicClassexternalizabledemo{PublicStaticvoidMain (string[] args)Throws exception{Ser ();Serialization of Dser ();Anti-sequence Session}PublicStaticvoidSer ()Throws exception{File File =New File ("D:" + File.separator +"Hello.txt"); ObjectOutputStream out =New ObjectOutputStream (New FileOutputStream (file)); Out.writeobject (New Person ("Rollen",20)); Out.close (); }PublicStaticvoidDser ()Throws exception{File File =New File ("D:" + File.separator +"Hello.txt"); ObjectInputStream input =New ObjectInputStream (New FileInputStream (file)); Object obj = Input.readobject (); Input.close (); System.out.println (obj); }}class Person implements externalizable{PublicPerson () {}PublicPerson (String name,int age) {THIS.name = name;This.age = age; }@OverridePublic StringToString () {Return"Name:" + name +"Age:" + ages; }This method, depending on the attributes or specific content that you want to save, is used when serializing@Override public void writeexternal (objectoutput out) throws ioexception{Out.writeobject (  THIS.name); Out.writeint (age); } //Replication This method, as needed to read the content of the deserialization session needs to @Override public  void readexternal (objectinput in) throws IOException, classnotfoundexception{ this.name = (String) in.readobject (); this.age = In.readint ();} private String name; private int age;}                

"Run Results":

Name: Rollen Age: 20

In this case, we have all the attributes preserved,

The operation of the serializable interface is actually the serialization of all the properties in an object, but it's also possible to use the Externalizable interface to serialize some of the properties, but it's a bit cumbersome to do

When we use the Serializable interface for serialization, we can use the Transient keyword if a property of an object does not want to be persisted by serialization:

Here's an example:

"Example 5"

Package IO;Import Java.io.File;Import Java.io.FileInputStream;Import Java.io.FileOutputStream;Import Java.io.ObjectInputStream;Import Java.io.ObjectOutputStream;Import java.io.Serializable;/** * Serialization and deserialization operations */PublicClassserdemo{PublicStaticvoidMain (string[] args)Throws exception{Ser ();Serialization of Dser ();Anti-sequence Session}PublicStaticvoidSer ()Throws exception{File File =New File ("D:" + File.separator +"Hello.txt"); ObjectOutputStream out =New ObjectOutputStream (New FileOutputStream (file)); Out.writeobject (New Person1 ("Rollen",20)); Out.close (); }PublicStaticvoidDser ()Throws exception{File File =New File ("D:" + File.separator +"Hello.txt"); ObjectInputStream input =New ObjectInputStream (New FileInputStream (file)); Object obj = Input.readobject (); Input.close (); System.out.println (obj); }}class Person1 implements serializable{public Person1 () {} public Person1 (String name, int age) { this.name = name; this.age = age;} @Override public String toString () { return ' name: ' + name + ' Age: ' + Ages;} //Note here private transient String name; private int age;}                 

"Run Results":

Name: null Age: 20

Finally, let's give an example of serializing a set of objects:

"Example 6"

Import Java.io.File;Import Java.io.FileInputStream;Import Java.io.FileOutputStream;Import Java.io.ObjectInputStream;Import Java.io.ObjectOutputStream;Import java.io.Serializable;/** * Serializing a group of objects */PublicClassserdemo1{PublicStaticvoidMain (string[] args)Throws exception{student[] Stu = {New Student ("Hello",20),New Student ("World",30),New Student ("Rollen",40)}; Ser (Stu); object[] obj = Dser ();Forint i =0; i < obj.length; ++i) {Student s = (Student) obj[i]; System.out.println (s); } }Serialization ofPublicStaticvoidSer (object[] obj)Throws exception{File File =New File ("D:" + File.separator +"Hello.txt"); ObjectOutputStream out =New ObjectOutputStream (New FileOutputStream (file)); Out.writeobject (obj); Out.close (); }DeserializationPublicStatic object[]Dser ()Throws exception{File File =New File ("D:" + File.separator +"Hello.txt"); ObjectInputStream input =New ObjectInputStream (new FileInputStream (file)); object[] obj = (object[]) input.readobject (); Input.close (); return obj;}} Class Student implements serializable{ public Student () {} public Student (String name, int age) { T His.name = name; this.age = age;} @Override public String toString () { return ' name: ' + name + ' Age: ' + Ages;} private String name; private int age;}                 

"Run Results":

姓名:  hello  年龄:20姓名:  world  年龄:30姓名:  rollen  年龄:40

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.