java - Why aren't my objects deserialized correctly? -


i have pretty simple class hierarchy:

public class dropdownoption<t> /* not implement serializable */ {     private t value;     private string label;      public dropdownoption() {         (null, null);     }      public dropdownoption(t value, string label) {         this.value = value;         this.label = label;      }      public t getvalue() {         return value;     }      public void setvalue(t value) {         this.value = value;     }      public string getlabel() {         return label;     }      public void setlabel(string label) {         this.label = label;     } }  /**  * convenience decorator  */ public class longiddropdownoption extends dropdownoption<long>      implements serializable {      private static final long serialversionuid = -3920989081132516015l;      public longiddropdownoption() {         super();             }      public longiddropdownoption(long value, string label) {         super(value, label);     }      public long getid() {         return getvalue();     }      public void setid(long id) {         super.setvalue(id);     } } 

when create new instance of longiddropdownoption, does implement serializable; serialize it; , deserialize -- deserialized object has both of fields set null:

public void testserialization() throws exception {     longiddropdownoption option = new longiddropdownoption(1l, "one");               bytearrayoutputstream buffer = new bytearrayoutputstream();     objectoutputstream os = new objectoutputstream(buffer);     os.writeobject(option);     os.close();      objectinputstream = new objectinputstream(         new bytearrayinputstream(buffer.tobytearray()));     longiddropdownoption result = (longiddropdownoption) is.readobject();     is.close();      assertnotnull(result);             assertequals("one", result.getlabel()); /** fails, label null */ } 

when make base class implement serializable, code starts working correctly. question is... why ?

as described here - http://java.sun.com/developer/technicalarticles/alt/serialization "one common reason override readobject , writeobject serialize data superclass not serializable itself".

the state think have in subclassed instance isn't visible serialization not going via api or reflection. far serialization process concerned state belongs in super class not implement serializable. lose it.

here's link java object serialization specification should explain it: http://download.oracle.com/javase/6/docs/platform/serialization/spec/serialtoc.html


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -