Resolving Objects

There may be occasions where you want to replace the objects read from the stream with other, alternative objects. Perhaps an old version of a program whose data you need to read used Franc objects, but the new version of the program uses Euro objects. The ObjectInputStream can replace each Franc object read with the equivalent Euro object.

Only trusted subclasses of ObjectInputStream may replace objects. A class is only trusted if it was loaded from the local class path; that is, the class loader returned by getClassLoader() is null. To make it possible for a trusted subclass to replace objects, you must first pass true to its enableResolveObject() method:

protected final boolean enableResolveObject(boolean enable) 
  throws SecurityException

Generally, you would do this in the constructor of any class that needed to replace objects. Once object replacement is enabled, whenever an object is read, it is passed to the ObjectInputStream subclass’s resolveObject() method before readObject() returns:

protected Object resolveObject(Object o) throws IOException

The resolveObject() method may return the object itself (the default behavior) or return a different object. Resolving objects is a tricky business. The substituted object must be compatible with the use of the original object, or errors will soon surface as the program tries to invoke methods or access fields that don’t exist. Most of the time, the replacing object is an instance of a subclass of the class of the replaced ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.