java - Issues with objects serialization -


i have issue when saving object serialization loading again..

first have class following string "a", "b", "c" saved data file...

later modified class has 1 more string "d". after load file saved before modified application not know new string "d"...

what best mechanism handle such issue... lengthy copy data old object new one... want make saved object know there structure changes...

any please...

use different serialversionuid tell system there's different version.

from javadoc on serializable:

serialization runtime associates each serializable class version number, called serialversionuid, used during deserialization verify sender , receiver of serialized object have loaded classes object compatible respect serialization. if receiver has loaded class object has different serialversionuid of corresponding sender's class, deserialization result in invalidclassexception. serializable class can declare own serialversionuid explicitly declaring field named "serialversionuid" must static, final, , of type long:

any-access-modifier static final long serialversionuid = 42l;

(markup me)

edit:

as alternative use field store version , deserialize despite class changes. in case new string should initialized null. check version see whether string present in previous version , null when saving or whether there structural change in between.

example:

class myobject {    private static final versionuid = 1;    private final int version;     private string a, b, c, d; //plus getters/setters;     public myobject() {      version = versionuid ; //needed if want load objects of different backward compatible versions , still know version after deserialization    }     public int getversion() {      return version;    } }   myobject readobjectofversion2 = ... ;//deserialize object of version 1 if( readobjectofversion2.getversion() > 1 ) {//assuming version 1 has a,b,c , version 2+ has d       string d = readobjectofversion2.getd(); } 

Comments