what is serialization and when is it going to be serialized?
Serialization is a mechanism for handling object flow, which is to stream the contents of an object and decompose the data into a byte stream for storage in a file or on a network.
We need to serialize the Java object when it is being streamed to or from the network.
How Java objects are serialized
First , implement serializable interface
PackageOrg.burning.sport.javase.serializable.demo1;Importjava.io.Serializable;Importjava.util.Date; Public classUserImplementsSerializable {Private Static Final LongSerialversionuid = -6330597348767194997l; PrivateString name; Private intAge ; PrivateDate birthday; Private transientString Gender; Setters (); getters (); toString ();}
PackageOrg.burning.sport.javase.serializable.demo1;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;Importjava.util.Date; Public classSerializabledemo { Public Static voidMain (string[] args) {User User=NewUser (); User.setname ("Hollis"); User.setgender ("Male"); User.setage (23); User.setbirthday (NewDate ()); System.out.println ("Serializable before:" +user); /*** Persist objects to a file*/ObjectOutputStream Oos=NULL; Try{Oos=NewObjectOutputStream (NewFileOutputStream ("Temp")); Oos.writeobject (user); } Catch(IOException e) {e.printstacktrace (); } finally { if(Oos! =NULL) { Try{oos.close (); } Catch(IOException e) {e.printstacktrace (); } } } /*** Read objects from the file*/ObjectInputStream ois=NULL; Try{ois=NewObjectInputStream (NewFileInputStream ("Temp")); User Readuser=(User) ois.readobject (); System.out.println ("Serializable after:" +readuser); } Catch(Exception e) {e.printstacktrace (); } finally { if(Ois! =NULL) { Try{ois.close (); } Catch(IOException e) {e.printstacktrace (); } } } }}//Output//serializable before:user{name= ' Hollis ', age=23, Birthday=sat May 11:35:06 CST 2018, gender= ' Male '}//serializable after:user{name= ' Hollis ', age=23, Birthday=sat May 11:35:06 CST 2018, gender= ' null '}Summary:
1. In Java, as long as a class implements the Java.io.Serializable interface, it can be serialized.
2, the object is serialized and deserialized by 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.
what's different about ArrayList serialization?
Let's take a look at ArrayList's source code:
Public class extends Abstractlist<e> implements list<e>, randomaccess, cloneable, java.io.serializable{ Private Static Final long serialversionuid = 8683452581122892189L; transient // Non-private to simplify nested class access Private int size;}
We see that elementdata is transient, so we don't think Elementdata is going to be preserved by serialization, so here's a demo:
PackageOrg.burning.sport.javase.serializable.demo1;Importorg.apache.commons.io.IOUtils;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;Importjava.util.ArrayList;Importjava.util.List; Public classArraylistserializabledemo { Public Static voidMain (string[] args)throwsexception{List<String> stringlist =NewArraylist<string>(); Stringlist.add ("Hello"); Stringlist.add ("World"); Stringlist.add ("Hollis"); Stringlist.add ("Chuang"); System.out.println ("Init stringlist" +stringlist); ObjectOutputStream ObjectOutputStream=NewObjectOutputStream (NewFileOutputStream ("Stringlist")); Objectoutputstream.writeobject (stringlist); ioutils.closequietly (ObjectOutputStream); File File=NewFile ("Stringlist"); ObjectInputStream ObjectInputStream=NewObjectInputStream (Newfileinputstream (file)); List<String> newstringlist = (list<string>) Objectinputstream.readobject (); ioutils.closequietly (ObjectInputStream); if(File.exists ()) {file.delete (); } System.out.println ("New Stringlist" +newstringlist); }}//output~//Init Stringlist[hello, World, Hollis, Chuang]//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?
The answer is in the ArrayList of WriteObject and ReadObject two methods:
Private voidReadObject (java.io.ObjectInputStream s)throwsjava.io.IOException, classnotfoundexception {elementdata=Empty_elementdata; //Read in size, and any hidden stuffS.defaultreadobject (); //Read in capacityS.readint ();//ignored if(Size > 0) { //Be-like clone (), allocate array based upon size not capacityensurecapacityinternal (size); Object[] a=Elementdata; //Read in all elements in the proper order. for(inti=0; i<size; i++) {A[i]=S.readobject (); } } }
Private voidWriteObject (java.io.ObjectOutputStream s)throwsjava.io.ioexception{//Write out element count, and any hidden stuff intExpectedmodcount =Modcount; S.defaultwriteobject (); //Write out size as capacity-behavioural compatibility with clone ()s.writeint (size); //Write elements in the proper order. for(inti=0; i<size; i++) {s.writeobject (elementdata[i]); } if(Modcount! =Expectedmodcount) { Throw Newconcurrentmodificationexception (); } }Summary:
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.
There is a question, why aarraylist to give elementdate to 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. 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.
So if you want to customize the serialization and deserialization strategy, you can mimic the ArrayList approach.
Objectouptstream&objectinputstream
One of the problems with the ArrayList example in the last section is that we don't see the invocation of WriteObject and ReadObject, how are these two methods called? The reason is Objectouptstream&objectinputstream.
Take a look at the Objectouptstream call stack? writeobject-> writeobject0-> writeordinaryobject-> writeserialdata-> invokeWriteObject. Here's a look at Invokewriteobject:
voidinvokewriteobject (Object obj, objectoutputstream out)throwsIOException, unsupportedoperationexception {if(Writeobjectmethod! =NULL) { Try{writeobjectmethod.invoke (obj,Newobject[]{out}); } Catch(InvocationTargetException ex) {throwable th=ex.gettargetexception (); if(thinstanceofIOException) { Throw(ioexception) th; } Else{throwmiscexception (TH); } } Catch(Illegalaccessexception ex) {//should not occur, as access checks has been suppressed Throw NewInternalerror (ex); } } Else { Throw Newunsupportedoperationexception (); } }
where writeobjectmethod.invoke (obj, new object[]{out}) is critical, the Writeobjectmethod method is called 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.
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
Https://gitee.com/play-happy/base-project Reference:
"1" blog, https://www.cnblogs.com/Qian123/articles/5665671.html
"2" blog, 8986720
javase-Serialization and deserialization