Removing Serialization and Deserialization

Suppose I serialize the following class (by putting a value in a field x

, say 5

) and before doing deserialization I delete the field x

and put a new field y

( int

or float

), what would be the result?

I believe the deserialization is successful and the field value y

will be the default, is that correct?

If that's correct, where will the if value be specified x

when going from a persistent object to a stateful object during serialization?

public class Cat implements Serializable{    
  private static final long serialVersionUID = 4231235177539824282L;  
  int x;
}

      

before deserialization:

public class Cat implements Serializable{    
  private static final long serialVersionUID = 4231235177539824282L;  
  float/int y;
}

      

+3


source to share


3 answers


The serialization spec details the inner workings of field deserialization (you can find it here: http://docs.oracle.com/javase/7/docs/platform/serialization/spec/input.html )

If you look at the "readObject method" section, it says:



Any field of an object that is not visible in the stream is set to its default value. Values ​​that appear in the stream but not in the object are discarded. This occurs primarily when a later version of the class wrote additional fields that were not found in the previous version.

So, in essence, the "x" field will have some value in the stream, but will be discarded, and the "y" field will be set to 0 (the default) since it is not visible in the stream.

+6


source


Jain007, I think you are likely to get an exception in this case since you "removed" the field.

FYI, the following incompatible changes that could lead to an exception: - Delete fields - Change class hierarchy - Change non-static to static - Change transient to transient - Change primitive field type



The following are compatible changes that do not affect the deserialization process: - Add fields - Change field from static to non-static - Change field from transient to non-transient - Add classes to the object tree

+2


source


The serialized data contains the variable names and signature that will be used during deserialization. The y value will be the default, as it is not described in the serialized data. the x value will be skipped, for example the new Cat class does not contain a variable with a suitable signature.
http://docs.oracle.com/javase/6/docs/platform/serialization/spec/protocol.html

+1


source







All Articles