2012-04-08 75 views
-1

我正在閱讀一篇文章說明..如果一個類的超類已經在Java中實現了Serializable接口,那麼它已經可以在Java中進行序列化,因爲你不能實現一個接口,所以它不可能使它不可序列化但是有一種方法可以避免新類的序列化。爲了避免Java序列化,你需要在你的類中實現writeObject()和readObject()方法,並且需要從這些方法中拋出NotSerializableException異常。這是定製java序列化過程的另一個好處,正如上面提到的問題所描述的那樣,並且通常會在面試過程中作爲後續問題提出。控制序列化

爲前..還有..超

class Animal implements Serializable 
{ 
int weight = 42; 
} 

and there is a subclass... 

class Dog extends Animal 
{ 
    private void writeObject(ObjectOutputStream o) 
          throws IOException, ClassNotFoundException 
    { 
     //throw nonserializable exception 
    } 

    private void readObject(ObjectInputStream o) 
     throws IOException, ClassNotFoundException 
    { 
      //throw nonserializable exception 
    } 

} 

可否請你從上面可以看出在狗類中的readObject()和writeObject()告訴我,我怎麼能寫指示代碼拋出nonserilizable異常..它像投擲非seriliable異常...請告知..

回答

1
class Dog extends Animal 
{ 
    private void writeObject(ObjectOutputStream o) 
          throws IOException, ClassNotFoundException 
    { 
     throw new NotSerializableException(); 
    } 

    private void readObject(ObjectInputStream o) 
     throws IOException, ClassNotFoundException 
    { 
     throw new NotSerializableException(); 
    } 

} 
+0

鑑於問題的存在,我建議閱讀異常和異常處理。 – trutheality 2012-04-08 04:52:59

+0

非常感謝,請指教我們是否需要一個catch塊.. !! – Neera 2012-04-08 04:54:36

+1

不在這裏。在這裏拋出一個異常點是爲了使序列化Dog不可能。它是試圖序列化需要捕獲異常的對象的代碼。 – trutheality 2012-04-08 05:00:21