java - 為什么Serializable中定義的Class 不能序列化?
問題描述
Fields in a Serializable class must themselves be either Serializable or transient even if the class is never explicitly serialized or deserialized. That’s because under load, most J2EE application frameworks flush objects to disk, and an allegedly Serializable object with non-transient, non-serializable data members could cause program crashes, and open the door to attackers.This rule raises an issue on non-Serializable fields, and on collection fields when they are not private (because they could be assigned non-Serializable values externally), and when they are assigned non-Serializable types within the class.Noncompliant Code Examplepublic class Address { //...}public class Person implements Serializable { private static final long serialVersionUID = 1905122041950251207L; private String name; private Address address; // Noncompliant; Address isn’t serializable}
問題解答
回答1:一個對象序列化時,按照Java默認的序列化規則,對象內的所有成員都要序列化,也就是說,這些Class都必須實現Serializable。
所以,你有兩種改法,一是Address實現Serializable接口,二是對Person中的address成員加上transient標記,這樣該成員就不會被序列化進去。
回答2:如果 address 成員需要進行序列化的話,則Address類也需要實現Serializable接口。如果 address 成員不需要進行序列化的話,可以加上transient關鍵字,則address成員不做序列化操作,值為null。如下:
public class Person implements Serializable { private static final long serialVersionUID = 1905122041950251207L; private String name; private transient Address address; // Noncompliant; Address isn’t serializable}
當然還有其他方式:比如實現Externalizable接口,重寫readExternal(ObjectInput in)和writeExternal(ObjectOutput out)方法。還有一個替代實現Externalizable接口方法,還是實現Serializable接口,添加writeObject(ObjectOutputStream obs)和readObject(ObjectInputStream ois)方法。
再說說為什么Address一定要實現Serializable,或者加上transient關鍵字Person才能進行序列化?先看看不做處理,使用 ObjectOutputStream 來持久化對象,拋出的異常
Exception in thread 'main' java.io.NotSerializableException
看ObjectOutputStream源碼:
/** * Underlying writeObject/writeUnshared implementation. */ private void writeObject0(Object obj, boolean unshared)throws IOException { //...... // remaining cases 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());} }} finally { depth--; bout.setBlockDataMode(oldMode);} }
從此可知, 如果被寫對象類型是String、Array、Enum、Serializable,就可以進行序列化,否則將拋出NotSerializableException。且在序列化對象時,不僅會序列化當前對象本身,還會對該對象引用的其它對象也進行序列化。
相關文章:
1. android - NavigationView 的側滑菜單中如何保存新增項(通過程序添加)2. mysql - select查詢多個紀錄的條件怎么寫3. linux - 編譯安裝mysql 5.6.234. 提示語法錯誤語法錯誤: unexpected ’abstract’ (T_ABSTRACT)5. 這段代碼既不提示錯誤也看不到結果,請老師明示錯在哪里,謝謝!6. php7.3.4中怎么開啟pdo驅動7. 老師 我是一個沒有學過php語言的準畢業生 我希望您能幫我一下8. ueditor上傳服務器提示后端配置項沒有正常加載,求助!!!!!9. tp5 不同控制器中的變量調用問題10. php - 第三方支付平臺在很短時間內多次異步通知,訂單多次確認收款
