问:分别说说下面程序代码段运行结果是什么?为什么?
public class Operation {
public boolean save() throws IOException {
State state = new State(27, "Demo");
ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File("./State.test")));
oo.writeObject(state);
oo.close();
return true;
}
public class State implements Serializable {
public static final long serialVersionUID = 123L;
public int age;
public String name;
public State(int age, String name) {
this.age = age;
this.name = name;
}
}
}
//调用
try {
Operation opt = new Operation();
opt.save();
} catch (Exception e) { //TODO }
}
答:上面程序片段运行报错如下:
java.io.NotSerializableException: Operation
因为内部类默认持有外部类的引用,外部类没有声明为可序列化,所以在序列化时导致崩溃,写代码要十分留意。
public class Operation {
public boolean save() throws IOException {
State state = new State(27, "Demo");
ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File("./State.test")));
oo.writeObject(state);
oo.close();
return true;
}
public static class State implements Serializable {
public static final long serialVersionUID = 123L;
public int age;
public String name;
public State(int age, String name) {
this.age = age;
this.name = name;
}
}
}
//调用
try {
Operation opt = new Operation();
opt.save();
} catch (Exception e) { //TODO }
}
答:上面程序片段运行序列化存储成功,静态内部类不回持有外部类的引用,所以序列化的是自己。