Static Class Variables and Serialization / Deserialization

From the tutorial SCJP 6 - the question arises about the output of the following code for serialization:

import java.io.*; public class TestClass { static public void main(String[] args) { SpecialSerial s = new SpecialSerial(); try { ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("myFile")); os.writeObject(s); os.close(); System.out.print(++sz + " "); s = null; // makes no difference whether this is here or not ObjectInputStream is = new ObjectInputStream(new FileInputStream("myFile")); SpecialSerial s2 = (SpecialSerial)is.readObject(); is.close(); System.out.println(s2.y + " " + s2.z); } catch (Exception e) {e.printStackTrace();} } } class SpecialSerial implements Serializable { transient int y = 7; static int z = 9; } 

Result: 10 0 10

The reason given is that the static variable z is not serialized, and I would not expect this.

The value of the static variable int z increases to 10 after the object has been written to the file, in the expression println ().

In this case, why does this not return to the original value of 9, when the class is deserialized or how the class is not created in the usual way, is the default int value for the class by default, and does not remain with an uninvolved value of 10 after deserialization? I would have thought that a value of 10 would be lost, but it is not.

Has anyone shed light? I stumble here in the dark, wrapping my fingers on this ...

+7
source share
2 answers

Mostly instances are serialized, not classes. Any static fields declared by the class are not subject to serialization / deserialization of the class instance. For z to reset to 9 the SpecialSerial class must be reloaded , this is another matter.

+3
source

The value s2.z is the value of the static member z of the SpecialSerial class, so it remains 10. z limited to the class, not the instance.

As if you did it

 ++SpecialSerial.z System.out.println(SpecialSerial.z) 

instead

 ++sz System.out.println(s2.z) 
+2
source

All Articles