• Post Reply Bookmark Topic Watch Topic
  • New Topic

static variables + serialization  RSS feed

 
rucha kulkarni
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Can we serialize static variables?

Please help
 
Guillaume Jourdan
Ranch Hand
Posts: 47
Eclipse IDE Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.sun.com wrote: When you serialize an instance of a class, the only things that are saved are the non-static and non-transient instance data.


cf : serialization java sun
 
rohit chavan
Ranch Hand
Posts: 133
Hibernate Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simply put, NO!
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Serialization is about storing an object's state and static is bounded to class like methods.
JVM encode only instance variables and class signature to a file as bytes. hence static can not be serialized
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Well, you can customize serialization by implementing your own readObject() and writeObject() methods, or implement the Externalizable interface. Both should enable you to force the serialization of static variables.

As everyone have already mentioned, by default, static variable doesn't get serialized.

Henry
 
rucha kulkarni
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for prompt response
 
R. Jain
Ranch Hand
Posts: 375
1
Java Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
rucha kulkarni wrote:Hi,

Can we serialize static variables?

Please help


Let's suppose, Java would have allowed you to serialize static variables (which of course it would never have).
As you must be knowing and already stated above, static variables are Class variables, and are not bound to any object.

1). Now if you serialize static variable, then it's state will be saved with the object instance.
2). Later on, when you deserialize the object instance, in the mean time, the static variable state might have been changed.
3). If you try to restore the static variable state through deseriazation. It will cause Havoc in the remaining Application. As that variable will be changed for all the code that is accessing it.

That is why Java does not allow you to serialize static variables..
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!