2
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 接口的类的引用!到底发生了什么?

4

1 回答 1

8

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

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

于 2013-07-16T18:49:27.110 回答