反序列化对象后静态变量的值是多少?
假设我创建了一个 B 类的实例,它有一个静态变量 x,在 B 类声明中分配了值 3。在 main() 方法中,我这样做:
B b = new B();
b.x = 7; //allowed to use an instance to set the static member value
在此之后,b 被序列化,然后反序列化。然后,出现以下行:
System.out.println ("static: " + b.x);
值是多少? 7还是3?
我知道静态变量没有序列化,但是,由于整个类只有一份静态成员的副本,并且该值设置为7,是否应该在反序列化实例后保留它?
Let's say that I create an instance of class B, which has an static variable x, assigned with a value of 3 in the class B declaration. In the main() method, I do this:
B b = new B();
b.x = 7; //allowed to use an instance to set the static member value
After this, b is serialized and then de-serialized. Then, the following line occurs:
System.out.println ("static: " + b.x);
What's the value? 7 or 3?
I know static variables are not serialized, however, since there is only one copy of the static member for the whole class, and the value is set to 7, should it be preserved after de-serializing an instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
发生的情况如下:
如果您想要您描述的逻辑,您需要添加另一个静态变量来计算创建的实例数量,并使用您的自定义逻辑覆盖
writeObject
和readObject
方法。Here's what happens:
If you want the logic you describe, you need to add another static variable which counts the number of instances created and override the
writeObject
andreadObject
methods with your custom logic.如果您在 JVM 的同一个实例中反序列化它,您的第二个代码段将返回 7。这是因为 bx 的值设置为 7。这并没有改变,因为B 的实例已被序列化并反序列化。
如果序列化该对象,关闭 JVM,启动一个新的 JVM,然后反序列化该对象(除了静态初始化之外不在任何地方设置 bx),bx 的值将为 3。
If you deserialize it in the same instance of the JVM, your second snippet will return 7. This is because the value of b.x is set to 7. That hasn't changed because an instance of B was serialized and deserialized.
If you serialize the object, shutdown the JVM, bring up a new JVM, and then deserialize the object (without setting b.x anywhere other than the static initialization), the value of b.x will be 3.
使用以下代码对内存流进行序列化、反序列化和对象化:
创建该类后,使用 JUnit 运行程序运行它并查看测试是否通过!如果您愿意,可以在一个测试用例中将结果写入文件。然后在另一个测试用例中,从文件中读取结果!
Use the following code to serialize and deserialize and object to / from an in-memory stream:
After creating that class, run it with a JUnit runner and see if the test passes! If you like, you can write the result to a file in one test case. Then in another test case, read the result from a file!
由于静态初始化程序仅运行一次,因此该值为
7
。Since static initializers run exactly once, the value is
7
.