我读到“序列化不适用于静态元素”——但下面的一个简单示例告诉我并非如此。
class superparent implements Serializable {
int data = 0;
public superparent(int data) {
this.data = data;
}
public int getdata() {
return data;
}
}
public class statichost implements Serializable {
int member = 0;
public static superparent s = new superparent(20);
public statichost(int data) {
this.member = data;
}
public static void main(String[] args) {
statichost c = new statichost(6);
try {
FileOutputStream fs = new FileOutputStream("testSer.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream("testSer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (statichost) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("after: contained data is " + c.s.getdata());
}
}
根据上面的语句,当我期望 0 时,输出会打印 20。我错过了什么吗?