Ale*_*lex 2 java io serialization 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
该程序正确执行并成功序列化对象ob.但我希望在运行时获得java.io.NotSerializableException.因为MyClass有没有实现Serializable接口的类的引用!真的发生了什么?
因为该字段为空.null可以很好地序列化.
序列化机制检查每个字段的实际具体类型,而不是其声明的类型.你可以有一个NotSerializable子类的实例,即Serializable,然后它也会很好地序列化.如果不是这种情况,您将无法序列化任何具有类型成员的对象,List例如,因为List没有实现Serializable.
| 归档时间: |
|
| 查看次数: |
77 次 |
| 最近记录: |