Java serializable interface (serialization) Understanding and custom serialization

Source: Internet
Author: User

1 Serializable interface

(1) simply put, it is possible to convert an object (the type of the flag Object) and its state to bytecode, save it (can be saved in the database, memory, files, etc.), and then you can restore its state at the appropriate time (that is, deserialization). Serialization not only can be done in this machine, but also can be operated via Network. It automatically masks differences in operating systems, byte order, and so On. For example, an object is generated on the Windows platform and serialized and then transmitted over a network to a UNIX machine, and the object can be reconstructed correctly on this UNIX machine (deserialization). Don't worry about how the data is represented on different machines, or about the order of bytes or any other Detail.

In addition, the following points should be understood:

A. The Java.io.Serializable interface does not have any method domain, and the class that implements it simply semantically indicates that it can be serialized.

B. No builders (or even the default builder) are called during the reassembly of a Serializable (serializable) object. The entire object is recovered from the data obtained from the Inputstream.

C. If a class is serializable, its subclasses are also serializable.

(2) Serialversionuid

The value of Serialversionuid is generated automatically by the Java Runtime Environment based on the internal details of the class. If the source code of the class is modified and then recompiled, the value of the serialversionuid of the newly generated class file may also Change.
The default value of the Serialversionuid class is entirely dependent on the implementation of the Java compiler, and compiling with different Java compilers for the same class may lead to different serialversionuid and possibly the Same. To improve the independence and certainty of serialversionuid, it is strongly recommended that the definition serialversionuid be displayed in a serializable class, giving it a definite value. There are two ways to explicitly define Serialversionuid:

A. In some cases, you want different versions of the class to be serializable compatible, so you need to ensure that the different versions of the class have the same serialversionuid;

B. In some cases, you do not want different versions of the class to be serializable compatible, so you need to ensure that different versions of the class have different serialversionuid.

2 Custom Serialization:

Custom serialization is determined by the Objectinput/outputstream at the time of serialization/deserialization by examining whether the class has the following methods (0 or more): execution order from top to bottom, serialization calls 1 and 2, deserialization calls 3 and 4 ; transient keyword when a field is declared as transient, the default serialization mechanism ignores the FIELD.

1Object writereplace () throws objectstreamexception; You can modify the serialized object by this method

2void writeobject (java.io.ObjectOutputStream Out) throws ioexception; The method calls Defaultwriteobject () using the default serialization method of writeobject, in addition to some other operations, such as adding additional serialized objects to the Output: out.writeobject ("XX")

3void readobject (java.io.ObjectInputStream In) throws Exception; Method calls Defaultreadobject () using the ReadObject default deserialization method, In addition to some other operations, such as reading additional serialized objects into the input: in.readobject ()

4Object readresolve () throws objectstreamexception; You can modify the returned object by this method

Example: the Singleton pattern class implements the serialization interface, and if the default serialization policy is used, the object returned in deserialization does not conform to the simple interest mode (reflection creates a new object, as in the Personsington object), You can implement custom serialization return results by modifying the serialized readresolve to achieve uniqueness of the Singleton object (which is equivalent to the 4 result of the one-way method without effect).

 public classPersonsingltonImplementsSerializable {    Private Static Final LongSerialversionuid = 1L; PrivateString name; PrivatePersonsinglton (String Name) { this. Name =name;    }; Private StaticPersonsinglton person =NULL; public Static synchronizedPersonsinglton getinstance () {if(person = =NULL)            returnperson =NewPersonsinglton ("cgl"); returnperson ; }    PrivateObject Writereplace ()throwsobjectstreamexception {System.out.println ("1 Write Replace start"); return  this;//can be modified to other objects}Private voidWriteObject (java.io.ObjectOutputStream Out)throwsIOException {System.out.println ("2 Write Object start"); Out.defaultwriteobject ();
Out.writeint (1); } Private voidReadObject (java.io.ObjectInputStream In)throwsioexception, classnotfoundexception {System.out.println ("3 Read Object start"); In.defaultreadobject ();
int I=in.readint (); } PrivateObject Readresolve ()throwsobjectstreamexception {System.out.println ("4 Read Resolve start"); returnPersonsinglton.getinstance ();//no Matter what the serialized operation is, The local singleton object is returned} public Static voidMain (string[] Args)throwsException {fileoutputstream out=NewFileOutputStream (NewFile ("d://person.dat")); ObjectOutputStream op=NewObjectOutputStream (out); Op.writeobject (personsinglton.getinstance ()); Op.close (); FileInputStream in=NewFileInputStream (NewFile ("d://person.dat")); ObjectInputStream Oi=NewObjectInputStream (in); Object person=Oi.readobject (); Inch=NewFileInputStream (NewFile ("d://person.dat")); Oi=NewObjectInputStream (in); Personsinglton Person1=(personsinglton) Oi.readobject (); System.out.println ("sington person hashcode:" +Person.hashcode ()); System.out.println ("sington Person1 hashcode:" +Person1.hashcode ()); System.out.println ("sington getinstance hashcode:" +personsinglton.getinstance (). hashcode ()); System.out.println (' Sington person equals: ' + (person = =personsinglton.getinstance ())); System.out.println ("person equals1:" + (person1 = =person )); }}

Operation Result:

1 Write replace Start
2 Write Object start
3 Read Object start
4 Read Resolve Start
3 Read Object start
4 Read Resolve Start
Sington person hashcode:1550089733
Sington Person1 hashcode:1550089733
Sington getinstance hashcode:1550089733
Sington person Equals:true
Person Equals1:true

3 Externalizable Interface

Externalizable inherits from serializable, and when the interface is used, the details of the serialization need to be done by the Programmer. If Writeexternal () and the readexternal () method do not do any processing, then the serialization behavior will not save/read any one field. The values for all fields in the result are Empty.
In addition, if externalizable is used for serialization, when the object is read, the parameterless constructor of the serialized class is called to create a new object, and the values of the fields of the saved object are then populated into the new object, respectively. For this reason, the class implementing the Externalizable interface must provide an argument-free constructor, and its access rights are PUBLIC.

Java serializable interface (serialization) Understanding and custom serialization

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.