GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Serialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Serialization " Watch "Serialization " New topic
Author

Serialization

Laloo Bond
Greenhorn

Joined: Jun 06, 2008
Posts: 5
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
Marshal

Joined: Mar 22, 2005
Posts: 42035
    
  64
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.


Ping & DNS - my free Android networking tools app
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

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!


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457
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


Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
 
GeeCON Prague 2014
 
subject: Serialization