Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java standard serialization order

I want to know in which order the attributes of the following example class would be serialized:

public class Example implements Serializable {

   private static final long serialVersionUID = 8845294179690379902L;

   public int score;
   public String name;
   public Date eventDate;
}

EDIT:

Why i wanna know this:

I got a serialized string in a file for a class of mine which has no implementation for readObject() or writeObject(). now that implementation changed ( some properties are gone ) and i want to write a readObject() method that handles the old serialized class.

There i would just read this property but wouldnt save it to the created object.

This is basically just for legacy i use a database now but need to support the old serialized files.

to write this readObject() i need the order of properties that in the stream.

like image 958
Ostkontentitan Avatar asked Nov 13 '13 08:11

Ostkontentitan


2 Answers

Based on a brief reading of the spec.

  • The fields are written in the order of the field descriptors the class descriptor

  • The field descriptors are in "canonical order" which is defined as follows:

    "The descriptors for primitive typed fields are written first sorted by field name followed by descriptors for the object typed fields sorted by field name. The names are sorted using String.compareTo."


(I suspect that the bit about the canonical order should not matter. The actual order of the fields in the serialization should be recoverable from the actual order of the field descriptors in the class descriptor in the same serialization. I suspect that the reason a canonical order is specified is that it affects the computed serialization id. But I could easily be wrong about this :-) )


Reference:

  • Java Object Serialization Specification - Section 4.3 and Section 6.4.1 (the comment on the "nowrclass" production)
like image 78
Stephen C Avatar answered Sep 28 '22 07:09

Stephen C


With regards to your original problem, some testing would suggest that if you've maintained your serialVersionUID and haven't removed fields containing values you need, you can probably just deserialize your old objects without error.

Any fields you no longer have will be ignored. Any new fields will be initialised to default values (e.g. null, or 0 etc.).

Bear in mind, this approach might violate constraints you've placed upon your class. For example, it may not be legal (in your eyes) to have null values in your fields.

Final warning: this is based on some testing of mine and research on the Internet. I haven't yet encountered any hard proof that this is guaranteed to work in all situations, nor that it is guaranteed to continue to work in the future. Tread carefully.

like image 24
Duncan Jones Avatar answered Sep 28 '22 06:09

Duncan Jones