T. Akhayo
T. Akhayo

Reputation: 411

Save java object tree with versioning?

I have a Java application which saves a object tree to file using default java object serialization (ObjectOutputStream and such). This works quite nicely.

The problem arises when I add a field to an object that is in the object tree. When I now load the old object tree I get a ClassException, which of course makes sense cause that object/class changed and the old class doesn't match the new class.

Now I can write different versions of my load method so that it can handle old object trees, but I suspect this might become not very easy to manage and maintain.

I was wondering if there is a better way to save a object tree in java which supports versioning?

Upvotes: 0

Views: 197

Answers (2)

YuvRAJ
YuvRAJ

Reputation: 94

use the readObject() and writeObject() methods of ObjectInputStream and ObjectOutputStream class in your Serializable class in order to define the default behavior when serializing/deserializing the object from your file ObjectOutputStream oos = new ObjectOutputStream(file/path/url); oos.writeObject(serialized Object); oos.close(); oos.flush(); ObjectInputStream ois = new ObjectInputStream(file/path/url/request); Object obj = (TypeCast to appropriate Object)ois.readObject();

Upvotes: 0

rongenre
rongenre

Reputation: 1334

You can use this approach (implementing readObject and writeObject) to handle schema migration: http://www.javaworld.com/javaworld/jw-02-2006/jw-0227-control.html

Upvotes: 2

Related Questions