In-depth analysis of the serialization and deserialization of Java

Source: Internet
Author: User

Read Catalogue


    • Serialization of Java Objects
      How to serialize and deserialize a Java object
      Related knowledge of serialization and deserialization
      Serialization of ArrayList
      ObjectOutputStream
      Summarize

Serialization is a means of persisting objects. Widely used in the network transmission, RMI and other scenarios. This article introduces the related contents of Java serialization by analyzing the serialization of ArrayList. The following issues are mainly involved:

  • How to implement the serialization of Java
  • Why the Java.io.Serializable interface is implemented to be serialized
  • What is the role of transient?
  • How to customize serialization policies
  • How the custom serialization policy is called
  • What are the benefits of ArrayList for serialization implementation?
Back to the top of the serialization of the Java object

The Java platform allows us to create reusable Java objects in memory, but in general, these objects can exist only when the JVM is running, that is, they will not have a longer life cycle than the JVM. In a real-world application, however, it is possible to require that the specified object be saved (persisted) after the JVM has stopped running, and that the saved object will be re-read in the future. The serialization of Java objects can help us implement this functionality.

Using Java object serialization, when you save an object, it saves its state as a set of bytes, and in the future, these bytes are assembled into objects. It is important to note that object serialization holds the "state" of the object, which is its member variable. It is to be concluded that object serialization does not focus on static variables in the class .

In addition to using object serialization when persisting objects, object serialization is used when RMI (remote method calls) is used, or when objects are passed through the network. The Java Serialization API provides a standard mechanism for handling object serialization, which is easy to use and will be covered in subsequent chapters of this article.

1 public class Arraylist<e> extends abstractlist<e>2         implements List<e>, Randomaccess, cloneable , Java.io.Serializable3 {4     private static final long Serialversionuid = 8683452581122892189l;5 6     transient Object[] Elementdata; Non-private to simplify nested class ACCESS7 8     private int size;9}
Back to top how to serialize and deserialize a Java object

In Java, as long as a class implements the Java.io.Serializable interface, it can be serialized. Here's a piece of code first:

Code 1 creates a user class for serialization and deserialization

 1 package com.hollis; 2 Import java.io.Serializable; 3 Import java.util.Date; 4 5/** 6 * Created by Hollis on 16/2/2. 7 */8 public class User implements serializable{9 private String name;10 private int age;11 private Date bi  rthday;12 private transient String gender;13 private static final long Serialversionuid = -6849794470754667710l;14 public string GetName () {name;17}18, public void SetName (string name) {Thi S.name = name;21}22 All public int getage () {return age;25}26, public void Setage (int. age) {  This.age = age;29}30 public Date getbirthday () {return birthday;33}34         void Setbirthday (Date birthday) {this.birthday = birthday;37}38-Public String Getgender () {40     return gender;41}42 public void Setgender (String gender) {This.gender = gender;45}46 47 @Override48 Public String toString () {"user{" +50 "name=" + name + '/' +51 ", age=" + AG  E +52 ", gender=" + Gender +53 ", birthday=" + Birthday +54 '} '; 55}56 }

Code 2 Demo for serialization and deserialization of user

 1 package com.hollis; 2 Import org.apache.commons.io.FileUtils; 3 Import org.apache.commons.io.IOUtils; 4 Import java.io.*; 5 Import Java.util.Date; 6 7/** 8 * Created by Hollis on 16/2/2. 9 */10 public class Serializabledemo {All public static void main (string[] args) {//initializes the Obje CT14 User user = new user (), User.setname ("Hollis"), Male User.setgender ("user.se");         Tage, User.setbirthday (New Date ()), System.out.println (user),//write Obj to File22 ObjectOutputStream Oos = null;23 try {The oos = new ObjectOutputStream (The New FileOutputStream ("tem         PFile ")); Oos.writeobject (user), and the catch (IOException e) {e.printstacktrace (); 28 } finally {ioutils.closequietly (oos);}31//read Obj from File33 File fi       Le = new File ("Tempfile"); ObjectInputStream ois = null;35  try {ois = new ObjectInputStream (new FileInputStream (file)), PNs User newuser = (User) ois.read Object (); System.out.println (NewUser); (IOException e) {+ E.printstacktrace () ; ClassNotFoundException} catch (e) {e.printstacktrace (); utils.closequietly (OIS); try {fileutils.forcedelete (file); tion e) {e.printstacktrace ();}50}51-}53}54//output-//user{name= ' hol Lis ', age=23, Gender=male, Birthday=tue Feb 17:37:38 CST 2016}56//user{name= ' Hollis ', age=23, Gender=null, Birthday=tu E Feb 17:37:38 CST 2016}
Back to top serialization and deserialization related knowledge

1. In Java, as long as a class implements the Java.io.Serializable interface, it can be serialized.

2. Serialization and deserialization of objects via ObjectOutputStream and ObjectInputStream

3, whether the virtual machine allows deserialization, not only depends on the class path and function code consistency, a very important point is that the serialization ID of two classes is consistent (that is, private static final long Serialversionuid)

4. Serialization does not save static variables.

5, in order to serialize the parent class object, it is necessary to let the parent class also implement the Serializable interface.

6, the function of the Transient keyword is to control the serialization of variables, before the variable declaration with the keyword, you can prevent the variable is serialized into the file, after being deserialized, the value of the Transient variable is set to the initial value, such as the int is 0, the object type is null.

7, the server side to the client to send serialized object data, some of the objects are sensitive, such as the password string, and so on, want to encrypt the password field at the time of serialization, and if the client has a decrypted key, only when the client is deserialized, the password can be read, This guarantees the data security of the serialized object to a certain extent.

Back to the top ArrayList serialization

Before introducing ArrayList serialization, consider an issue:

How to customize the serialization and deserialization policies

With this problem, we look at the source code of Java.util.ArrayList

Code 3

1 public class Arraylist<e> extends abstractlist<e>2         implements List<e>, Randomaccess, cloneable , Java.io.Serializable3 {4     private static final long Serialversionuid = 8683452581122892189l;5     transient Object [] elementdata; Non-private to simplify nested class ACCESS6     private int Size;7}

I omitted the other member variables, from the above code can know that ArrayList implementation of the Java.io.Serializable interface, then we can serialize and deserialize it. Because Elementdata is transient, we think that this member variable will not be serialized and preserved. Let's write a demo to verify our ideas:

Code 4

 1 public static void main (string[] args) throws IOException, ClassNotFoundException {2 list<string> String List = new arraylist<string> (); 3 Stringlist.add ("Hello"); 4 Stringlist.add ("World"); 5 Stringlist.add ("Hollis"); 6 Stringlist.add ("Chuang"); 7 System.out.println ("Init stringlist" + stringlist); 8 ObjectOutputStream ObjectOutputStream = new ObjectOutputStream (New FileOutputStream ("Stringlist")); 9 Objectoutputstream.writeobject (stringlist), Ioutils.close (objectoutputstream), file file = new File ("Stringlist"), ObjectInputStream ObjectInputStream = new ObjectInputStream (new FileInputStream (File)) ; list<string> newstringlist = (list<string>) objectinputstream.readobject (); IOUtils.close (ObjectInputStream); if (File.exists ()) {file.delete ();}19 System.out.println ("N    EW stringlist "+ newstringlist); 20 }21//init Stringlist[hello, World, Hollis, chuang]22//new Stringlist[hello, World, Hollis, Chuang] 

People who know ArrayList know that the bottom layer of ArrayList is implemented by arrays. Then the array elementdata is actually used to save the elements in the list. By the way this property is declared, we know that he cannot be persisted by serialization. So why is the result of code 4 preserving the elements in the list by serialization and deserialization?

WriteObject and ReadObject methods

A method is defined in ArrayList: WriteObject and ReadObject.

Here is the first conclusion:

In the serialization process, if the writeobject and ReadObject methods are defined in the serialized class, the virtual opportunity attempts to invoke the WriteObject and ReadObject methods in the object class for user-defined serialization and deserialization.

If there is no such method, the default call is the Defaultwriteobject method of ObjectOutputStream and the Defaultreadobject method of ObjectInputStream.

The user-defined WriteObject and ReadObject methods allow the user to control the serialization process, such as the ability to dynamically change the serialized value during serialization.

Take a look at the specific implementations of these two methods:

Code 5

1 private void ReadObject (Java.io.ObjectInputStream s) 2         throws Java.io.IOException, ClassNotFoundException {3         elementdata = empty_elementdata; 4  5         //Read in size, and any hidden stuff 6         s.defaultreadobject (); 7
   
    8         //Read in Capacity 9         s.readint ();//IGNORED10         if (Size > 0) {             //is like Clone (), Allocate AR Ray based upon size not CAPACITY13             ensurecapacityinternal (size);             object[] A = elementdata;16             //Read In all elements in the proper order.17 for             (int i=0; i<size; i++) {a[i                 ] = S.readobject ();             }20         }21     }
   

Code 6

1 private void WriteObject (Java.io.ObjectOutputStream s) 2         throws java.io.ioexception{3         //Write out element cou NT, and any hidden stuff 4         int expectedmodcount = modcount; 5         s.defaultwriteobject (); 6  7         //Write out Siz  E as capacity for behavioural compatibility with clone () 8         s.writeint (size), 9/Write out all elements in the         Proper order.11 for         (int i=0; i<size; i++) {s.writeobject             (Elementdata[i]),         }14         if ( Modcount! = Expectedmodcount) {+             -throw new Concurrentmodificationexception ();         }18     }

So why is ArrayList going to serialize this way?

Why transient

ArrayList is actually a dynamic array, and each time the set length value is automatically increased after it is full, 99 null elements are serialized if the array auto-grow length is set to 100 and only one element is actually placed. To ensure that so many nulls are not serialized at the time of serialization, ArrayList sets the element array to transient.

Why WriteObject and ReadObject

As I said earlier, in order to prevent an array containing a large number of empty objects from being serialized, ArrayList uses transient to declare elementdata in order to optimize storage.

However, as a collection, it is also necessary to ensure that elements in the serialization process are persisted, so that the elements are preserved by overriding the WriteObject and ReadObject methods.

The WriteObject method saves the traversal of elements in the Elementdata array to the output stream (ObjectOutputStream).

The ReadObject method reads the object from the input stream (ObjectInputStream) and saves the assignment to the Elementdata array.

At this point, let's try to answer the question we just raised:

How to customize the serialization and deserialization policies

A: You can add the WriteObject and ReadObject methods in the serialized class. So here's the question:

Although the WriteObject and ReadObject methods are written in ArrayList, these two methods are not shown to be called.

So if a class contains WriteObject and ReadObject methods, how are these two methods called? Back to top ObjectOutputStream

From code 4, we can see that the serialization process of the object is achieved through ObjectOutputStream and objectinputputstream, so with just the question, let's analyze ArrayList writeobject and How exactly is the ReadObject method called?

To save space, here is the call stack for ObjectOutputStream writeobject:

Writeobject-&gt; Writeobject0-&gt;writeordinaryobject-&gt;writeserialdata-&gt;invokewriteobject

Here's a look at Invokewriteobject:

1 void Invokewriteobject (Object obj, objectoutputstream out) 2         throws IOException, Unsupportedoperationexception 3<  c1/>{4         if (Writeobjectmethod! = null) {5             try {6                 writeobjectmethod.invoke (obj, new object[]{out}); 7             }  catch (InvocationTargetException ex) {8                 throwable th = ex.gettargetexception (); 9                 if (th instanceof IOException) {Ten                     throw (IOException) th;11                 } else {                     throwmiscexception (th);                 }14             } catch ( Illegalaccessexception ex) {                 should not occur, as access checks has been suppressed16                 throw new Internaler Ror (ex),             }18         } else {The             throw new Unsupportedoperationexception ();         }21     }

where Writeobjectmethod.invoke (obj, new object[]{out}); is critical to call the Writeobjectmethod method by reflection. The official explanation for this writeobjectmethod:

Class-defined WriteObject method, or null if none

In our case, this method is the WriteObject method we defined in ArrayList. is called by reflection.

At this point, let's try to answer the question we just raised:

If a class contains WriteObject and ReadObject methods, how are these two methods called?

A: When using the WriteObject method of ObjectOutputStream and the ReadObject method of ObjectInputStream, it is called by reflection.

So far, we've covered the serialization of ArrayList. Well, don't know if anyone raises such a question:

Serializable is clearly an empty interface, how does it guarantee that only the method that implements the interface can be serialized and deserialized?

Definition of the Serializable interface:

1 public interface Serializable {2}

The reader can try to remove the code 1 from the inherited serializable, and then execute the 2, which throws the Java.io.NotSerializableException.

In fact, this question is also very good answer, we go back to just objectoutputstream of the writeobject call stack:

Writeobject-&gt; Writeobject0-&gt;writeordinaryobject-&gt;writeserialdata-&gt;invokewriteobject

There is a piece of code in the WriteObject0 method:

1 if (obj instanceof String) {2                 writestring (string) obj, unshared), 3             } else if (Cl.isarray ()) {4                 Writearra Y (obj, desc, unshared); 5             } else if (obj instanceof Enum) {6                 writeenum ((enum<?>) obj, desc, unshared); 7             } else if (obj Instanc EOF Serializable) {8                 writeordinaryobject (obj, desc, unshared); 9             } else {ten                 if (extendeddebuginfo) {11                     throw new Notserializableexception (                         cl.getname () + "/n" + debuginfostack.tostring ()), or                 else {14< C13/>throw New Notserializableexception (Cl.getname ());                 }16             }

When the serialization operation is performed, it is determined whether the class to be serialized is an enum, an array, and a serializable type, and if not, throws the notserializableexception directly.

Back to top of the summary

1. If a class wants to be serialized, the serializable interface needs to be implemented. Otherwise, the notserializableexception exception is thrown because the type is checked during the serialization operation, requiring that the class being serialized must belong to either of the Enum, array, and serializable types.

2. By adding the keyword before the variable declaration, you can prevent the variable from being serialized into the file.

3. Add WriteObject and ReadObject methods to the class to implement a custom serialization strategy

From:http://www.cnblogs.com/qian123/articles/5665671.html

In-depth analysis of the serialization and deserialization of Java

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.