Does a deserialized object retain static values?

Here is a very simple test program:

public class Body implements Serializable { static int bod = 5; int dis = -1; public void show(){ System.out.println("Result: " + bod + " & " + dis); } } public class Testing { public static void main(String[] args) { Body theBody = new Body(); theBody.show(); try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.dat")); out.writeObject(theBody); out.close(); ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.dat")); Body bodyDouble = (Body)in.readObject(); in.close(); bodyDouble.show(); } catch(IOException e) { } catch(ClassNotFoundException e) { } } } 

But I do not understand why his conclusion:

 Result: 5 & -1 Result: 5 & -1 

Since static members are not serialized and therefore get default values, I expected a different output:

 Result: 5 & -1 Result: 0 & -1 

How did the deserialized object get the correct static field value?

I made this test application because I need to serialize several objects with several static fields to make deep copies (and, of course, I need to be sure that the copies have the same values โ€‹โ€‹of static fields, since they are used as array indices).

And now I'm completely confused about what happens after deserialization. On the one hand, static members are not serialized, but, on the other hand, as the example shows, static members somehow retain their values. I suspect this has something to readObject() to a Body object, but I'm not sure.

+6
source share
1 answer

How did the deserialized object get the correct static field value?

Since static field values โ€‹โ€‹have not changed between serialization and deserialization:

You run your test in the application . Consequently, static members of a class retain their meaning. The class itself does not reload or initialize - it is still the same.

You must separate your test in two separate applications:

  • Let one application serialize an object
  • Let one application deserialize an object

Then run these two applications one by one. Then you will see that the static members will not be restored in the second application.

In addition, in your code above, you can also set the static field to a different value before deserialization - you will see that the variable still has this value after deserialization.

On a side note, never execute ... catch(IOException e) {} ... - at least print a stack trace with e.printStackTrace() .

+6
source

All Articles