Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize static data members of a Java class?

When we serialize objects, static members are not serialized, but if we need to do so, is there any way out?

like image 231
Maddy.Shik Avatar asked Jun 17 '09 16:06

Maddy.Shik


People also ask

Can we serialize static members in Java?

In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI). But, static variables belong to class therefore, you cannot serialize static variables in Java.

Can we save static data member using serialization?

Static data members and transient data members are not saved via Serialization process.So, if you don't want to save value of a non-static data member then make it transient.

Is it static member variables are serialized?

Static Variables: These variables are not serialized, So during deserialization static variable value will loaded from the class.

Do static fields get serialized?

static fields aren't serialized.


1 Answers

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.

like image 58
Kathy Van Stone Avatar answered Oct 01 '22 20:10

Kathy Van Stone