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

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.