【问题标题】:Why did not I get NotSerializableException?为什么我没有得到 NotSerializableException?
【发布时间】:2013-07-15 02:38:34
【问题描述】:
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 接口的类!到底发生了什么?

【问题讨论】:

  • 尝试实例化field

标签: java serialization io notserializableexception


【解决方案1】:

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

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

【讨论】:

  • 惊呆了!不知道这种情况......非常感谢!
猜你喜欢
  • 2021-04-20
  • 1970-01-01
  • 2020-11-19
  • 2015-06-03
  • 1970-01-01
  • 1970-01-01
  • 2015-11-26
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多