有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我没有得到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(); 
      }
   }
}

此程序正确执行并成功序列化对象ob。但我希望得到java。木卫一。运行时的NotSerializableException。因为MyClass具有类的引用,该类不实现可序列化接口!到底发生了什么


共 (1) 个答案

  1. # 1 楼答案

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

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