O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required