Search code examples
javaserializationjava-custom-serialization

How do writeObject and readObject work?


When I read the source code of JDK 6.0 I found these two methods in ArrayList. You see they are both private. But after searching, I didn't find any other methods calling either of them. I also considered the native methods, but still couldn't find any. These two methods seem to deal with the IO, but they are never called.

So, my question is, how do they work? Is there any other way to call private methods?

/**
 * Save the state of the <tt>ArrayList</tt> instance to a stream (that is, serialize it).
 */
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException;

/**
 * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is, deserialize it).
 */
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException;

Solution

  • These two methods are used in serializable class to customize the serialization (aka Customize the Default Protocol).

    Text from article:

    There is, however, a strange yet crafty solution. By using a built-in feature of the serialization mechanism, developers can enhance the normal process by providing two methods inside their class files. Those methods are:

    1. private void writeObject(ObjectOutputStream out) throws IOException;
    2. private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

    Notice that both methods are (and must be) declared private, proving that neither method is inherited and overridden or overloaded. The trick here is that the virtual machine will automatically check to see if either method is declared during the corresponding method call. The virtual machine can call private methods of your class whenever it wants but no other objects can.