java - Handle deserialization when datatype of class field changed -


i have serializable class.

public class customer  implements externalizable {  private static final long serialversionuid = 1l;      private string id;     private string name;      public string getid() {         return id;     }      public void setid(string id) {         this.id = id;     }      public  string getname() {         return name;     }       public void setname( string name) {         this.name = name;     }       @override     public string tostring() {         return "id : "+id+" name : "+name ;     }      @override     public void readexternal(objectinput in) throws ioexception,             classnotfoundexception {             this.setid((string) in.readobject());             this.setname((string) in.readobject());          }      @override     public void writeexternal(objectoutput out) throws ioexception {         system.out.println("reached here");         out.writeobject(id);         out.writeobject(name);     }   } 

i have serialized object of class file. have changed datatype of name string list. while deserializing, getting class cast exception because not able convert string list. thinking of changing version of class every time change made class in readexternal can handle explicitly. while idea might able work simple classes fail in case of larger complicated classes. can please provide simpler solution this.

thanks

you have manage different possibilities (and perform appropiate conversion) yourself.

@override public void readexternal(objectinput in) throws ioexception,   classnotfoundexception {   this.setid((string) in.readobject());   object namefield = in.readobject();   if (namefield != null) {     boolean resolved = false;     if (namefield instanceof string) {       arraylist<string> list = new arraylist<string>(); // or whatever want converting string list.       list.add((string)namefield);       this.setname(list);       resolved = true;     }     if (namefield instanceof list) {       this.setname((list<string>) namefield);       resolved = true;     }     if (!resolved) {       throw new exception("could not deserialize " + namefield + " name attribute");     }   } } 

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -