Java Serialization Technology

Source: Internet
Author: User
Tags object serialization

What is serialization and deserialization

Serialization (serialization) is a process of describing objects in a sequence of bytes, and deserializing deserialization is a process of re-building these bytes into an object.

What happens when serialization is required

    • When you want to save objects in memory to a file or database (data persistence);
    • The use of serialization to achieve remote communication, that is, the transmission of the object's byte sequence on the network;

How to implement serialization

It is possible to implement the serializable interface for a class that requires serialization, and there is no method in the serializable interface that can be understood as a token that indicates that the class can be serialized.

Examples of serialization and deserialization

If we want to serialize an object, we first create some outputstream (such as FileOutputStream, Bytearrayoutputstream, etc.), These outputstream are then encapsulated in a objectoutputstream. At this point, you simply call the WriteObject () method to serialize the object and send it to OutputStream (remember: Object serialization is byte-based and cannot use character-based hierarchies such as reader and writer). The process of deserializing (reverting a sequence to an object) requires that a inputstream (such as FileInputStream, Bytearrayinputstream, and so on) be encapsulated within the ObjectInputStream. Then call ReadObject ().

public class Serialize implementsserializable{private static final long Serialversionuid = -5211389707739541364l; public int num = 1390; public voidSerialized () {try{FileOutputStream fos = new FileOutputStream ("Serialize.obj"); ObjectOutputStream Oos = new ObjectOutputStream (FOS); Serialize Serialize = new  Serialize (); Oos.writeobject (Serialize); Oos.flush (); Oos.close ();  fos.close (); System.out.println ("Serialization End" ),} catch  (FileNotFoundException e) {e.printstacktrace ();} Catch  ( IOException e) {e.printstacktrace ();}} public void  deserialized () {Serialize Serialize = null ; try  {FileInputStream fis = new FileInputStream ("Serialize.obj" ); ObjectInputStream ois = new  objectinputstream (FIS); serialize =  (serialize) Ois.readobject (); Ois.close (); Fis.close (); SYSTEM.OUT.PRINTLN ("deserialization End" );} catch (ClassNotFoundException |  IOException e) {e.printstacktrace ();} System.out.println (Serialize.num); public static void  main (string[] args) {Serialize Serialize = new  Serialize (); serialize.serialized (); Seri Alize.deserialized (); } } 

The serialized data contains the information

Here is an example that reads the serialize.obj information from the above example:

public class Readserialize {public        static void main (string[] args) {          try {              File File = new file (" Serialize.obj ");              InputStream in = new fileinputstream (file);              byte buff[] = new byte[1024]; int len = 0; while (len = in.read (buff))!=-1) {for (int i=0;i<len;i++
           
            ) {System.out.printf ("%02x"
            , Buff[i]);} System.out.println (); }} catch (FileNotFoundException e) {e.printstacktrace ();} catch    
              

Operation Result:

AC ED xx (   6F 6D 2E)------------------7A 2 (   6E) 6D,  6E  

Analytical:
The first part is the serialized file header
AC Ed:stream_magic Declaration uses a serialization protocol
XX 05:stream_version Serialization Protocol version
73:tc_object declares this to be a new object
The second part is the description of the serialization class
72:tc_classdesc statement here begins a new class
The length of the 17:class name is 23 bytes
6F 6D 2E All-in-one-6C-7A-2E-----------------6C--7A 65: Class name (ASCII: com.serialize.Serialize)
B7 AD 6C AC 0E D0 8c:serialversionuid
02: Tag number, change value Declaration object support serialization
00 01: The class contains a number of fields of 1
The third part is the description of each property item in the object
49: Domain type, representing I, int type (also: 44, check ASCII code table D, for double type)
00 03: The length of the domain name word is 3
6E the name of the 6d:num property
Part IV outputs the object's parent class information description, there is no parent class, and if so, the data format is the same as the second part
78:tc_endblockdata, object block receive flag
70:tc_null, stating that there are no other super-class flags
Part V The actual value of the property of the output object, and if the property item is an object, the object is also serialized here, and the rule is the same as the 2nd part.
Value of 6e:1390 in XX

Relationship of pre-and post-serialized objects
When serializing a deep copy, the object address after deserialization is different from the original.

Break a singleton pattern

Serialization and deserialization can break a single case. This is illustrated by the relationship between the pre-serialized and the serialized objects.

How can I prevent a single case from being destroyed? Add the Readresolve method to the class of the Singleton. No new objects can be produced when the objectiputstream is called.

View the source code of Objectiputstream.class, in which there is a passage:

Deserializing an object via readunshared invalidates the stream handle associated with the returned object. Note that this on itself does not always guarantee that the reference returned by readunshared is unique; The deserialized object may define a Readresolve method which returns an object visible to other parties, or read Unshared may return a Class object or an Enum constant obtainable elsewhere in the stream or through external means. If the deserialized object defines a Readresolve method and the invocation of that method returns an array, then Readunsha Red returns a shallow clone of that array; This guarantees the returned

Array object is unique and cannot being obtained a second time from an invocation of ReadObject or readunshared on the object InputStream, even if the underlying data stream has been manipulated.

    Private Object readresolve ()      {          return  instance;      }  

Serialization ID

The serialization ID provides two build strategies under Eclipse, one fixed 1L, one randomly generating a non-repeating long type of data (actually generated using the JDK tool), where there is a recommendation that, if there is no special requirement, it is available with the default 1L, which ensures that the code is consistent When deserialization succeeds. This can also be the cause of serialization and deserialization failures because different serialization IDs cannot be serialized and deserialized.

Whether static variables can be serialized

Serialization ignores static variables, that is, serialization does not save the state of static variables. Static members are class-level, so they cannot be serialized. That is, serializing the state of the object is not the state of the class. The meaning of this cannot be serialized is that the serialized information does not contain this static member field. The variable after transient cannot be serialized either.

Transient usage Summary

    • Once the variable is transient decorated, the variable will no longer be part of the object's persistence, and the variable content cannot be accessed after serialization.
    • The Transient keyword can only modify variables, not methods and classes. Note that local variables cannot be modified by the transient keyword. If the variable is a user-defined class variable, the class needs to implement the serializable interface.
    • Variables modified by the Transient keyword can no longer be serialized, and a static variable cannot be serialized, whether or not it is transient decorated.

Summarize

    • When the parent class inherits the serializable interface, all subclasses can be serialized.
    • Subclasses implement the Serializable interface, the parent class does not, the attributes in the parent class cannot be serialized (no error, no data is lost), but the attributes in the subclass are still correctly serialized
    • If the serialized property is an object, the object must also implement the Serializable interface, otherwise it will error.
    • When deserializing, if the properties of an object are modified or truncated, the modified part of the property is lost but does not cause an error.
    • When deserializing, if Serialversionuid is modified, the deserialization fails
    • When an instance variable of an object references another object, serializing the object also serializes the reference object
    • The variable after static,transient cannot be serialized

Suggestions

In the Java environment, Java serialization can work very well, but in a multi-language environment, with Java serialization of storage, it is difficult to use other languages to restore the results, in this case, or to try to store common data structures, such as JSON or XML structure data, there are better serialization tools, such as Google's protobuf.

Java Serialization Technology

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.