Java static serialization rules? Java static serialization rules? java java

Java static serialization rules?


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.


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 InvalidClassExceptionwould occur.


static fields are ignored for serialization.

Updated to say static rather than transient as I originally intended...