序列化是一種對象持久化的手段。廣泛應用在網絡傳輸、RMI等場景中。本文經過分析ArrayList的序列化來介紹Java序列化的相關內容。主要涉及到如下幾個問題:java
- 怎麼實現Java的序列化
- 爲何實現了java.io.Serializable接口才能被序列化
- transient的做用是什麼
- 怎麼自定義序列化策略
- 自定義的序列化策略是如何被調用的
- ArrayList對序列化的實現有什麼好處
Java平臺容許咱們在內存中建立可複用的Java對象,但通常狀況下,只有當JVM處於運行時,這些對象纔可能存在,即,這些對象的生命週期不會比JVM的生命週期更長。但在現實應用中,就可能要求在JVM中止運行以後可以保存(持久化)指定的對象,並在未來從新讀取被保存的對象。Java對象序列化就可以幫助咱們實現該功能。apache
使用Java對象序列化,在保存對象時,會把其狀態保存爲一組字節,在將來,再將這些字節組裝成對象。必須注意地是,對象序列化保存的是對象的」狀態」,即它的成員變量。由此可知, 對象序列化不會關注類中的靜態變量 。數組
除了在持久化對象時會用到對象序列化以外,當使用RMI(遠程方法調用),或在網絡中傳遞對象時,都會用到對象序列化。Java序列化API爲處理對象序列化提供了一個標準機制,該API簡單易用,在本文的後續章節中將會陸續講到。安全
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; transient Object[] elementData; // non-private to simplify nested class access private int size; }
在Java中,只要一個類實現了 java.io.Serializable 接口,那麼它就能夠被序列化。這裏先來一段代碼:服務器
code 1 建立一個User類,用於序列化及反序列化網絡
package com.hollis; import java.io.Serializable; import java.util.Date; /** * Created by hollis on 16/2/2. */ public class User implements Serializable{ private String name; private int age; private Date birthday; private transient String gender; private static final long serialVersionUID = -6849794470754667710L; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "User{" + "name='" + name + '/'' + ", age=" + age + ", gender=" + gender + ", birthday=" + birthday + '}'; } }
code 2 對User進行序列化及反序列化的Demodom
package com.hollis; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import java.io.*; import java.util.Date; /** * Created by hollis on 16/2/2. */ public class SerializableDemo { public static void main(String[] args) { //Initializes The Object User user = new User(); user.setName("hollis"); user.setGender("male"); user.setAge(23); user.setBirthday(new Date()); System.out.println(user); //Write Obj to File ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("tempFile")); oos.writeObject(user); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(oos); } //Read Obj from File File file = new File("tempFile"); ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream(file)); User newUser = (User) ois.readObject(); System.out.println(newUser); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(ois); try { FileUtils.forceDelete(file); } catch (IOException e) { e.printStackTrace(); } } } } //output //User{name='hollis', age=23, gender=male, birthday=Tue Feb 02 17:37:38 CST 2016} //User{name='hollis', age=23, gender=null, birthday=Tue Feb 02 17:37:38 CST 2016}
一、在Java中,只要一個類實現了 java.io.Serializable 接口,那麼它就能夠被序列化。ide
二、經過 ObjectOutputStream 和 ObjectInputStream 對對象進行序列化及反序列化優化
三、虛擬機是否容許反序列化,不只取決於類路徑和功能代碼是否一致,一個很是重要的一點是兩個類的序列化 ID 是否一致(就是 private static final long serialVersionUID )ui
四、序列化並不保存靜態變量。
五、要想將父類對象也序列化,就須要讓父類也實現 Serializable 接口。
六、Transient 關鍵字的做用是控制變量的序列化,在變量聲明前加上該關鍵字,能夠阻止該變量被序列化到文件中,在被反序列化後,transient 變量的值被設爲初始值,如 int 型的是 0,對象型的是 null。
七、服務器端給客戶端發送序列化對象數據,對象中有一些數據是敏感的,好比密碼字符串等,但願對該密碼字段在序列化時,進行加密,而客戶端若是擁有解密的密鑰,只有在客戶端進行反序列化時,才能夠對密碼進行讀取,這樣能夠必定程度保證序列化對象的數據安全。
在介紹ArrayList序列化以前,先來考慮一個問題:
帶着這個問題,咱們來看 java.util.ArrayList 的源碼
code 3
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; transient Object[] elementData; // non-private to simplify nested class access private int size; }
筆者省略了其餘成員變量,從上面的代碼中能夠知道ArrayList實現了 java.io.Serializable 接口,那麼咱們就能夠對它進行序列化及反序列化。由於elementData是 transient 的,因此咱們認爲這個成員變量不會被序列化而保留下來。咱們寫一個Demo,驗證一下咱們的想法:
code 4
public static void main(String[] args) throws IOException, ClassNotFoundException { List<String> stringList = new ArrayList<String>(); stringList.add("hello"); stringList.add("world"); stringList.add("hollis"); stringList.add("chuang"); System.out.println("init StringList" + stringList); ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("stringlist")); 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(); } System.out.println("new StringList" + newStringList); } //init StringList[hello, world, hollis, chuang] //new StringList[hello, world, hollis, chuang]
瞭解ArrayList的人都知道,ArrayList底層是經過數組實現的。那麼數組 elementData 其實就是用來保存列表中的元素的。經過該屬性的聲明方式咱們知道,他是沒法經過序列化持久化下來的。那麼爲何code 4的結果卻經過序列化和反序列化把List中的元素保留下來了呢?
在ArrayList中定義了來個方法: writeObject 和 readObject 。
這裏先給出結論:
在序列化過程當中,若是被序列化的類中定義了writeObject 和 readObject 方法,虛擬機會試圖調用對象類裏的 writeObject 和 readObject 方法,進行用戶自定義的序列化和反序列化。
若是沒有這樣的方法,則默認調用是 ObjectOutputStream 的 defaultWriteObject 方法以及 ObjectInputStream 的 defaultReadObject 方法。
用戶自定義的 writeObject 和 readObject 方法能夠容許用戶控制序列化的過程,好比能夠在序列化的過程當中動態改變序列化的數值。
來看一下這兩個方法的具體實現:
code 5
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { elementData = EMPTY_ELEMENTDATA; // Read in size, and any hidden stuff s.defaultReadObject(); // Read in capacity s.readInt(); // ignored if (size > 0) { // be like clone(), allocate array based upon size not capacity ensureCapacityInternal(size); Object[] a = elementData; // Read in all elements in the proper order. for (int i=0; i<size; i++) { a[i] = s.readObject(); } } }
code 6
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff int expectedModCount = modCount; s.defaultWriteObject(); // Write out size as capacity for behavioural compatibility with clone() s.writeInt(size); // Write out all elements in the proper order. for (int i=0; i<size; i++) { s.writeObject(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } }
那麼爲何ArrayList要用這種方式來實現序列化呢?
ArrayList其實是動態數組,每次在放滿之後自動增加設定的長度值,若是數組自動增加長度設爲100,而實際只放了一個元素,那就會序列化99個null元素。爲了保證在序列化的時候不會將這麼多null同時進行序列化,ArrayList把元素數組設置爲transient。
前面說過,爲了防止一個包含大量空對象的數組被序列化,爲了優化存儲,因此,ArrayList使用 transient 來聲明 elementData 。
可是,做爲一個集合,在序列化過程當中還必須保證其中的元素能夠被持久化下來,因此,經過重寫 writeObject 和 readObject 方法的方式把其中的元素保留下來。
writeObject 方法把 elementData 數組中的元素遍歷的保存到輸出流(ObjectOutputStream)中。
readObject 方法從輸入流(ObjectInputStream)中讀出對象並保存賦值到 elementData 數組中。
至此,咱們先試着來回答剛剛提出的問題:
如何自定義的序列化和反序列化策略
答:能夠經過在被序列化的類中增長writeObject 和 readObject方法。那麼問題又來了:
雖然ArrayList中寫了writeObject 和 readObject 方法,可是這兩個方法並無顯示的被調用啊。
從code 4中,咱們能夠看出,對象的序列化過程經過ObjectOutputStream和ObjectInputputStream來實現的,那麼帶着剛剛的問題,咱們來分析一下ArrayList中的writeObject 和 readObject 方法究竟是如何被調用的呢?
爲了節省篇幅,這裏給出ObjectOutputStream的writeObject的調用棧:
writeObject —> writeObject0 —>writeOrdinaryObject—>writeSerialData—>invokeWriteObject
這裏看一下invokeWriteObject:
void invokeWriteObject(Object obj, ObjectOutputStream out) throws IOException, UnsupportedOperationException { if (writeObjectMethod != null) { try { writeObjectMethod.invoke(obj, new Object[]{ out }); } catch (InvocationTargetException ex) { Throwable th = ex.getTargetException(); if (th instanceof IOException) { throw (IOException) th; } else { throwMiscException(th); } } catch (IllegalAccessException ex) { // should not occur, as access checks have been suppressed throw new InternalError(ex); } } else { throw new UnsupportedOperationException(); } }
其中 writeObjectMethod.invoke(obj, new Object[]{ out }); 是關鍵,經過反射的方式調用writeObjectMethod方法。官方是這麼解釋這個writeObjectMethod的:
class-defined writeObject method, or null if none
在咱們的例子中,這個方法就是咱們在ArrayList中定義的writeObject方法。經過反射的方式被調用了。
至此,咱們先試着來回答剛剛提出的問題:
答:在使用ObjectOutputStream的writeObject方法和ObjectInputStream的readObject方法時,會經過反射的方式調用。
至此,咱們已經介紹完了ArrayList的序列化方式。那麼,不知道有沒有人提出這樣的疑問:
Serializable明明就是一個空的接口,它是怎麼保證只有實現了該接口的方法才能進行序列化與反序列化的呢?
Serializable接口的定義:
public interface Serializable { }
讀者能夠嘗試把code 1中的繼承Serializable的代碼去掉,再執行code 2,會拋出 java.io.NotSerializableException 。
其實這個問題也很好回答,咱們再回到剛剛ObjectOutputStream的writeObject的調用棧:
writeObject —> writeObject0 —>writeOrdinaryObject—>writeSerialData—>invokeWriteObject
writeObject0方法中有這麼一段代碼:
if (obj instanceof String) { writeString((String) obj, unshared); } else if (cl.isArray()) { writeArray(obj, desc, unshared); } else if (obj instanceof Enum) { writeEnum((Enum<?>) obj, desc, unshared); } else if (obj instanceof Serializable) { writeOrdinaryObject(obj, desc, unshared); } else { if (extendedDebugInfo) { throw new NotSerializableException( cl.getName() + "/n" + debugInfoStack.toString()); } else { throw new NotSerializableException(cl.getName()); } }
在進行序列化操做時,會判斷要被序列化的類是不是Enum、Array和Serializable類型,若是不是則直接拋出 NotSerializableException 。
一、若是一個類想被序列化,須要實現Serializable接口。不然將拋出 NotSerializableException 異常,這是由於,在序列化操做過程當中會對類型進行檢查,要求被序列化的類必須屬於Enum、Array和Serializable類型其中的任何一種。
二、在變量聲明前加上該關鍵字,能夠阻止該變量被序列化到文件中。
三、在類中增長writeObject 和 readObject 方法能夠實現自定義序列化策略