静态变量的值如何在序列化过程中持久化(如果完全持久化)。我在栈上读过类似的问题,它说静态变量本质上是瞬态的,即它们的状态或当前值未序列化。
我只是做一个非常简单的示例,我将一个类序列化并保存到文件中,然后再次从文件中重构该类。令人惊讶的是,我发现静态变量的值在序列化发生时和发生时都被保存了。
这是怎么发生的。这是因为类模板及其实例信息是在序列化期间保存的。这是代码片段-
public class ChildClass implements Serializable, Cloneable{
/**
*
*/
private static final long serialVersionUID = 5041762167843978459L;
private static int staticState;
int state = 0;
public ChildClass(int state){
this.state = state;
staticState = 10001;
}
public String toString() {
return "state" + state + " " + "static state " + staticState;
}
public static void setStaticState(int state) {
staticState = state;
}
这是我的主班
public class TestRunner {
/**
* @param args
*/
public static void main(String[] args) {
new TestRunner().run();
}
public TestRunner() {
}
public void run() {
ChildClass c = new ChildClass(101);
ChildClass.setStaticState(999999);
FileOutputStream fo = null;
ObjectOutputStream os = null;
File file = new File("F:\\test");
try {
fo = new FileOutputStream(file);
os = new ObjectOutputStream(fo);
os.writeObject(c);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(null != os)os.close();
if(null != fo) fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileInputStream fi = null;
ObjectInputStream ois = null;
ChildClass streamed;
try {
fi = new FileInputStream(file);
ois = new ObjectInputStream(fi);
Object o = ois.readObject();
if(o instanceof ChildClass){
streamed = (ChildClass)o;
//ChildClass cloned = streamed.clone();
System.out.println(streamed.toString());
}
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(null != ois)ois.close();
if(null != fi) fi.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注意:代码没有错。我只是想知道如何在类’ChildClass’中保存静态变量’staticState’的值。如果我通过网络传输此序列化数据,那么将保存状态吗?