Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java static serialization rules?

I'm working on a save state serialization with a few static methods and fields. I could have sworn though that serialization and static's caused mayhem. Should I make all static's transient? And will inflating the calls restore the statics as normal?

like image 467
ahodder Avatar asked Jun 21 '11 17:06

ahodder


People also ask

Can we serialize static methods 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.

Do static fields get serialized?

static fields aren't serialized.

What Cannot be serialized in Java?

If any class (or parent) is not explicitly marked Serializable, then it isn't. If you mark a class as Serializable then all of its members each need to follow these same rules for themselves.

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.


2 Answers

statics are implicitly transient, so you don't need to declare them as such.

Serialization is for serializing instances, not classes. static fields (methods are irrelevant since they are part of the class definition so they aren't serialized) will be reinitialized to whatever value they are set to when the class is loaded.

If you have a mutable static field, then the changes made to that value will be lost.

like image 94
Robin Avatar answered Sep 27 '22 22:09

Robin


The short rules can be as follows:

1. static variable are not saved during serialization. And on the contrary, during de-serialization process, the static variables are initiated from the class level initialization.

2. static and transient keywords based variables are both ignored during serialization.

3. Class name and serialVersionUID are both serialized as stream of bytes and when de-serialized the serialVersionUID , read from the source, is compared with local class same static variable. That is why serialVersionUID is declared as static public final so that no further object needs to be created for comparing these versionUID(s).

  • If in case any difference is found, then a InvalidClassException would occur.
like image 37
Gagandeep Avatar answered Sep 27 '22 22:09

Gagandeep