• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Serialization

 
Laloo Bond
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static variables cannot be serialized, as serialization is meant for only objects and not for class.

Now my doubt is, if we use the static variables in the class, and while serializing the object , the value of static variable may be different and when deserializing the object the static variable may be different.

How it will restore the correct value for the object which is deserialized?

Do we have to serialise it manually ?How it will work?
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no single "correct" value for static fields. Serialization simply ignores them. So if an object is deserialized, the static fields of that class remain what they were before the deserialization. If you want fields that can change on a per-object basis, they can't be static.
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's true. As Ulf said, the static values never come into picture of the serialization at all. They are treated as if the "instance variables marked as transient"!

So, no need to bother!
 
Henry Wong
author
Marshal
Pie
Posts: 20881
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do we have to serialise it manually ?How it will work?


If you really want to serialize/deserialize static variables, then you can implement the readObject() and writeObject() methods for the class. (technically, it is not "override" since these are private methods).

However, keep in mind, that when you deserialize, you will be changing a static variable -- which is a variable used by every object of that class type.

Henry
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can customize serialization (as stated above),

but what would happen if you unserialized two different objects that both tried to write to the static value? non-deterministic behavior.

bad.

you should question the design and use of the static variable
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic