The use of Java Foundation---->serializable

Source: Internet
Author: User
Tags object serialization

In this tutorial we build a Java project to experience the use of serialization serializable, the principle of serialization, and the customization of serialization see my other blog (Java advanced---->serializable serialized source code Analysis)

Directory Navigation

    1. A brief description of serializable serialization
    2. serializable a serialized code instance
    3. externalizable A serialized code instance
    4. Friendship Link

A brief description of serializable serialization

First, the simple introduction of persistence:

Persistence means that the object's "Time to live" does not depend on whether the program is executing-it exists or "survives" between each invocation of the program. A "durable" effect is accomplished by serializing an object, writing it to disk, and recovering that object later when the program is re-invoked.

Second, the language has added the concept of object serialization, you can provide support for the two main features:

    • Remote Method Invocation (RMI) enables objects that would otherwise exist on other machines to behave as if they were on the local machine. When you send a message to a remote object, you need to transfer the parameters and return values through object serialization.
    • When a Java Bean is used, its state information is usually configured during design time. After the program is started, this state information must be saved so that the program can be resumed after it starts, and the specific work is done by the object serialization.

Iii. Some notes of serializable:

    • The serialization of the object is very simple, just the object implements the serializable interface (the interface is only a token, there is no method)
    • The serialized objects include basic data types, all collection classes, and many other things, as well as class objects
    • Object serialization not only preserves the "panorama" of an object, but also keeps track of all the handles contained within the object and saves those objects, and then tracks the handles contained within each object.
    • A variable that is decorated with the transient keyword, which is not serialized during the serialization of an object.

Iv. Steps for serialization:

    • First, you create some OutputStream objects: outputstream outputstream = new FileOutputStream ("Output.txt")
    • Encapsulate it inside the ObjectOutputStream object: ObjectOutputStream objectoutputstream = new ObjectOutputStream (outputstream);
    • Then simply call WriteObject () to complete the serialization of the object and send it to OutputStream:objectOutputStream.writeObject (object);
    • Finally, don't forget to close the resource: Objectoutputstream.close (), OutputStream. Close ();

V. Steps to deserialize:

    • First, you create some OutputStream objects: InputStream inputstream= new FileInputStream ("Output.txt")
    • Encapsulate it inside the ObjectInputStream object: ObjectInputStream objectinputstream= new ObjectInputStream (InputStream);
    • You can then simply call WriteObject () to complete the deserialization of the object: Objectinputstream.readobject ();
    • Finally, do not forget to close the resources: Objectinputstream.close (), Inputstream.close ();

Serializable a serialized Code instance

Project structure as follows, source code download see Huhx Links:

First, we build a man class that implements the serializable interface for the test of the person class:

 PackageCom.huhx.model;Importjava.io.Serializable; Public classMansImplementsSerializable {Private Static Final LongSerialversionuid = 1L; PrivateString username; PrivateString password;  PublicMan (string username, string password) { This. Username =username;  This. Password =password; }     PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }}

Second, we create a person class for serialization:

 PackageCom.huhx.model;Importjava.io.Serializable; Public classPersonImplementsSerializable {Private Static Final LongSerialversionuid = 1L; PrivateMans Man; PrivateString username; Private transient intAge ;  PublicPerson () {System.out.println ("Person Constru"); }         PublicPerson (Mans man, String username,intAge ) {         This. Man =Man ;  This. Username =username;  This. Age =Age ; }     PublicMan Getman () {returnMan ; }     Public voidSetman (man Mans) { This. Man =Man ; }     PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }}

C. Write a test class that contains the main method: Maintest, whose writeserializableobject is used to serialize the object:

//Serializable: Serialization of Objects Public Static voidWriteserializableobject () {Try{man mans=NewMan ("Huhx", "123456"); Person Person=NewPerson (Mans, "Liu Li", 21); ObjectOutputStream ObjectOutputStream=NewObjectOutputStream (NewFileOutputStream ("Output.txt")); Objectoutputstream.writeobject ("String");        Objectoutputstream.writeobject (person);    Objectoutputstream.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }}

Test class Maintest, whose readserializableobject is used for deserializing objects:

//Serializable: Deserializing objects Public Static voidReadserializableobject () {Try{ObjectInputStream ObjectInputStream=NewObjectInputStream (NewFileInputStream ("Output.txt")); String String=(String) objectinputstream.readobject (); Person Person=(person) objectinputstream.readobject ();        Objectinputstream.close (); System.out.println (String+ ", Age:" + person.getage () + ", Mans Username:" +Person.getman (). GetUserName ()); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); }}

Five, in the main method to add the above two methods of operation, the results are as follows:

    • The person class contains a reference to man, and when the person is serialized, the result can be known that the man is also serialized.
    • The WriteObject method can pass in a string because the string is first a class, and then it is the serializable interface that implements the
    • The age field in the person class is transient, which you can see from the print result, that when you serialize the person person = The new person (man, "Liu Li", 21) object, it is not serialized. If transient modifies the type of object, then the printed result will be null

Externalizable a serialized Code instance

First, let's look at the definition of externalizable: inherit the Serializable interface

 Public Interface extends java.io.Serializable

First, we create a user class that implements the Externalizable: Rewrite the two methods readexternal and writeexternal

 PackageCom.huhx.model;Importjava.io.Externalizable;Importjava.io.IOException;ImportJava.io.ObjectInput;ImportJava.io.ObjectOutput; Public classUserImplementsexternalizable {PrivateString User;  PublicString GetUser () {returnuser; }     Public intGetage () {returnAge ; }    Private intAge ;  PublicUser () {System.out.println ("User constructor."); }     PublicUser (String user,intAge ) {System.out.println ("User constructor.");  This. user =user;  This. Age =Age ; } @Override Public voidReadexternal (ObjectInput in)throwsIOException, ClassNotFoundException {System.out.println ("Read external."); User=(String) in.readobject (); Age=In.readint (); } @Override Public voidWriteexternal (ObjectOutput out)throwsIOException {System.out.println ("Write external.");        Out.writeobject (user);    Out.writeint (age); }}

Second, add method Writeexternalizableobject in Maintest, used to serialize object user

//externalizable of serialized objects Public Static voidWriteexternalizableobject () {User User=NewUser ("Huhx", 22); Try{ObjectOutputStream ObjectOutputStream=NewObjectOutputStream (NewFileOutputStream ("Externalizable.txt"));        Objectoutputstream.writeobject (user);    Objectoutputstream.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }}

Third, add method Writeexternalizableobject in Maintest, for deserializing object user

//externalizable the deserialized object Public Static voidReadexternalizableobject () {Try{ObjectInputStream ObjectInputStream=NewObjectInputStream (NewFileInputStream ("Externalizable.txt")); User User=(User) objectinputstream.readobject ();        Objectinputstream.close (); System.out.println ("Name:" + user.getuser () + ", Age:" +user.getage ()); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); }}

Four, in the main method to add the above two methods of operation, the results are as follows:

  

    • First User user = new User ("Huhx", 22); The user's parameter constructor is executed
    • When executing to the writeobject (user) method, the user implements the Externalizable interface, so its writeexternal executes,
    • In the user's Readexternal method called the ObjectInput ReadObject method, in this method through the reflection mechanism to create the user's instance, called the user's parameter-free constructor.
    • Then , when the ReadObject method executes, the Readexternal method of the user class is also executed first. This will be discussed in the subsequent source code analysis

Friendship Link
    • This article test code: Access Password 12BB
    • The principle of serialization analysis of Java Advanced---->serializable serialization of source code

The use of Java Foundation---->serializable

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.