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 Classes

The readObject() method of java.io.ObjectInputStream only creates new objects from known classes. It doesn’t load classes. If a class for an object can’t be found, readObject() throws a ClassNotFoundException. It specifically does not attempt to read the class data from the object stream. This is limiting for some things you might want to do, particularly RMI. Therefore, trusted subclasses of ObjectInputStream may be allowed to load classes from the stream or some other source like a URL. Specifically, a class is trusted if, and only if, it was loaded from the local class path; that is, the ClassLoader object returned by getClassLoader() is null.

Two protected methods are involved. The first is the annotateClass() method of ObjectOutputStream :

protected void annotateClass(Class c) throws IOException

In ObjectOutputStream this is a do-nothing method. A subclass of ObjectOutputStream can provide a different implementation that provides data for the class. For instance, this might be the byte code of the class itself or a URL where the class can be found.

Standard object input streams cannot read and resolve the class data written by annotateClass(). For each subclass of ObjectOutputStream that overrides annotateClass(), there will normally be a corresponding subclass of ObjectInputStream that implements the resolveClass() method:

protected Class resolveClass(ObjectStreamClass v) 
  throws IOException, ClassNotFoundException

In java.io.ObjectInputStream, this is a do-nothing ...

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