简体   繁体   English

为什么我没有得到NotSerializableException?

[英]Why did not I get NotSerializableException?

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(); 
      }
   }
}

This program executes correctly and successfully serializes the object ob . 该程序正确执行并成功序列化对象ob But I expected to get java.io.NotSerializableException at runtime. 但我希望在运行时获得java.io.NotSerializableException Because MyClass has reference of class which does not implement the Serializable interface! 因为MyClass具有不实现Serializable接口的类的引用! What is really going on? 真的发生了什么?

Because the field is null. 因为该字段为空。 And null can be serialized fine. null可以很好地序列化。

The serialization mechanism checks the actual, concrete type of each field, and not its declared type. 序列化机制检查每个字段的实际具体类型,而不是其声明的类型。 You could have an instance of a subclass of NotSerializable, that is Serializable, and it would then serialize fine as well. 你可以有一个NotSerializable子类的实例,即Serializable,然后它也会很好地序列化。 If that was not the case, you would not be able to serialize any object having a member of type List for example, because List doesn't implement Serializable. 如果不是这种情况,您将无法序列化任何具有List类型成员的对象,因为List不实现Serializable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM