When we serialize objects, static members are not serialized, but if we need to do so, is there any way out?
The first question is why you need to serialize the static members?
Static members are associated with the class, not the instances, so it does not make sense to include them when serializing an instance.
The first solution is to make those members not static. Or, if those members are the same in the original class and the target class (same class, but possibly different runtime environments), don't serialize them at all.
I have a few thoughts on how one could send across static members, but I first need to see the use case, as in all cases that means updating the target class, and I haven't found a good reason to do so.
Static members belong to the class, not to the individual objects.
You should reconsider your data structure.
You can control serialization by implementing:
private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;
There's a full description of serialization http://java.sun.com/developer/technicalArticles/Programming/serialization/.
As other answers have said, it doesn't really make sense to serialize statics as it's the object not the class you're serializing and needing to do so smells like you've got other issues with your code to me.
Good answers and comments--don't do it. But how?
Chances are you would be best off creating an object to hold all your "Statics". That object should probably have any static methods from your class as well.
Every instance of your class can hold this other class--or if you really have to you can make it a singleton that any member can access.
After you do this refactor, you will find that it should have been done this way all along. You may even find that some of your previous design constraints that were bothering you at a subconsicionce level have vanished.
You'll probably find that this solution also solves other Serialization problems you hadn't even noticed yet.
Folks, static doesn't mean IMMUTABLE. For instance, I may want to serialize the whole state of the computation (yes, including static fields -- counters, etc) to resume later, after JVM and/or host computer restarted.
The right answer to that, as already said, is to use Externalizable, not Serializable, interface. Then you have a complete control on what and how you externalize.
yes we can serialize the static variables but we can write our own writeObject() and readObject(). i think this can solves the problem