今天闲下来,想到一道面试题,
对象A实现了序列化接口,
对象B为A的实例变量,未序列化,当把A对象持久化到文件中时,就会抛出NotSerializableException
对象A实现了序列化接口,
对象B为A的实例变量,未序列化,当把A对象持久化到文件中时,就会抛出NotSerializableException
也就是说,要持久化对象,或传输时,需要对其所引用的实例进行序列化,
public class NotSerializ {
public String name = "aaaa";
}
public class MySerializ implements Serializable{
private static final long serialVersionUID = -7918349215312458095L;
public NotSerializ not;
public long num = 9;
public static void main(String[] args) {
MySerializ mySerializ = new MySerializ();
mySerializ.doSerializ();
mySerializ.readSerializ();
}
private void readSerializ() {
File file = new File("text.txt");
try {
FileInputStream out = new FileInputStream(file);
ObjectInputStream oin = new ObjectInputStream (out);
Object o = oin.readObject();
System.out.println(((MySerializ)o).not.name);
System.out.println(((MySerializ)o).num);
oin.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void doSerializ() {
MySerializ o = new MySerializ();
o.num = 3;
o.not = new NotSerializ();
File file = new File("text.txt");
try {
FileOutputStream out = new FileOutputStream(file);
ObjectOutputStream oput = new ObjectOutputStream (out);
oput.writeObject(o);
oput.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}