java静态变量序列化

如何在序列化期间保持静态变量的值(如果完全持久化)。 我已经在堆栈上读到了类似的问题,它表示静态变量本质上是瞬态的,即它们的状态或当前值不是序列化的。

我只是做了一个非常简单的例子,我将一个类序列化并将其保存到一个文件中,然后再次从文件重构该类。我惊奇地发现静态变量的值和序列化发生时的值都被保存了。

这是怎么发生的。 这是因为在序列化过程中会保存类模板及其实例信息。 这是代码片段 –

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’的值。 如果我通过网络传输此序列化数据,那么状态是否会被保存

静态字段值未序列化。 输出正在打印静态字段的新值,因为您将其修改为999999,但在解除分类之前,您从未将其值重置为旧值。 由于该字段是静态的,因此新值将反映在ChildClass 任何实例中。

要正确断言字段未序列化,请在反序列化对象之前将值重置为10001,您会注意到它的值不是999999。

 ... ChildClass.setStaticState(10001); FileInputStream fi = null; ObjectInputStream ois = null; ChildClass streamed; ... // when de-serializing, the below will print "state101 static state 10001" System.out.println(streamed.toString());