zilcuanu
zilcuanu

Reputation: 3715

methods declaration related to serialization in java

I was going through the java documentation of Serialization and found that if we need to explicitly implement the serialization and deserialization we need to implement the following methods:

private void writeObject(java.io.ObjectOutputStream out)
 throws IOException

private void readObject(java.io.ObjectInputStream in)
 throws IOException, ClassNotFoundException;

private void readObjectNoData()
 throws ObjectStreamException;

Could someone please let me know who calls these methods as these methods are not there in the Object class as well as Serializable interface (since it is a marker interface).

Upvotes: 2

Views: 63

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36630

Could someone please let me know who calls these methods as these methods are not there in the Object class as well as Serializable interface

Even if they would be there, they would not be callable from outside in the "normal" way since they are private (finally, they could not even be inherited).

As @Andreas (not me :) ) said in the comments, the runtime library calls them through reflection. You can find the relevant code in the Java runtime library in the jdk/src/java.base/share/classes/java/io/ObjectStreamClass.java (link might change over time) source file:

...
private Method writeObjectMethod;
private Method readObjectMethod;
private Method readObjectNoDataMethod;

...

writeObjectMethod = getPrivateMethod(cl, "writeObject",
                            new Class<?>[] { ObjectOutputStream.class },
                            Void.TYPE);
readObjectMethod = getPrivateMethod(cl, "readObject",
                            new Class<?>[] { ObjectInputStream.class },
                            Void.TYPE);
readObjectNoDataMethod = getPrivateMethod(
                            cl, "readObjectNoData", null, Void.TYPE);
...

getPrivateMethod() is a utility method which looks up a given method for a Class through the reflection API.

If one of those Method references is not null, this means that the corresponding class contains that method, and it can be called like

...
writeObjectMethod.invoke(obj, new Object[]{ out });
...

at a later time.

Upvotes: 3

Related Questions