2013-07-16 54 views
1
class NotSerializable {} 

class MyClass implements Serializable { 
    private NotSerializable field; // class NotSerializable does not implement Serializable!! 
} 

public class Runner { 
    public static void main(String[] args) { 
     MyClass ob = new MyClass(); 

     try { 
     FileOutputStream fs = new FileOutputStream("testSer.ser"); 
     ObjectOutputStream os = new ObjectOutputStream(fs); 
     os.writeObject(ob); 
     os.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
     FileInputStream fis = new FileInputStream("testSer.ser"); 
     ObjectInputStream ois = new ObjectInputStream(fis); 
     MyClass copyOb = (MyClass) ois.readObject(); 
     ois.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

该程序正确执行并成功序列化对象ob。但我期望在运行时得到java.io.NotSerializableException。因为MyClass有没有实现Serializable接口的类的引用!究竟发生了什么?为什么我没有得到NotSerializableException?

+0

尝试实例化'field'。 –

回答

7

因为该字段为空。并且null可以很好地序列化。

序列化机制检查每个字段的实际具体类型,而不是其声明的类型。你可以有一个NotSerializable的子类的实例,也就是Serializable,然后它会很好地序列化。如果情况并非如此,那么您将无法序列化具有List类型成员的任何对象,因为List未实现Serializable。

+0

愣住了!不知道这种情况...非常感谢你! – Alex

+0

+1获取有用的信息。 –