Serialization of Java Learning Note objects

Source: Internet
Author: User
Tags object serialization

Object serialization is a way to turn an object into a binary data stream. If an object of a class wants to be serialized, it implements the serializable interface, which is an identity interface (only the interface is defined and no method is defined), indicating that the object has the ability to be serialized.

After implementing the Serializable interface, it indicates that the class has the ability to be transmitted by the data stream, and if you want to enter and output, use two classes: ObjectOutputStream and ObjectInputStream

When serializing, only attributes are serialized

If a property of an object does not want to be serialized, it can be declared using the Transient keyword (this property is transparent and is not considered for serialization).

Serializable interface uses:

ImportJava.io.*; Public classTest { Public Static voidMain (string[] args)throwsException {Try{objectoutputstream Oos=NULL; ObjectInputStream Ois=NULL; File F=NewFile ("E:\\java\\person.txt"); OutputStream OS=NewFileOutputStream (f); InputStream is=NewFileInputStream (f); Oos=Newobjectoutputstream (OS); Ois=NewObjectInputStream (IS); Person P1=NewPerson (23, "Baby", 180.00);            Oos.writeobject (p1);            Oos.close (); Person P2=(person) ois.readobject ();          Ois.close ();                System.out.println (p2); }Catch(IOException e) {e.printstacktrace (); }    }    }classPersonImplementsSerializable {intAge = 8;    String name; transient Doubleheight = 170;//The variable declared by transient is not considered at serialization, so it is the default value 0 when deserializingPerson (intAge,string name,Doubleheight) {         This. Age =Age ;  This. Name =name;  This. Height =height; }             PublicString toString () {return"Name:" + This. Name + "Age:" + This. Age + "Height:" + This. Height; }}

Serialization of Java Learning Note objects

Related Article

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.