Java Serialization

May 25, 2021 at 14:40

Java Object Serialization

The specification can be found here for Java 11.

Serialization interface

If we simply inherit this interface we are declaring our class can be serialized.

class Car(val name : String) : Serializable

readObject and writeObject

If we have these two methods on our class we can control how we serialize the class.

These are found via reflection and are not members of the Serialization interface. We must implement exactly the signature:

private void writeObject(ObjectOutputStream stream)
    throws IOException;

as per Section 2.3.

For example:

class Car(var name: String) : Serializable {
    private fun writeObject(oos : ObjectOutputStream) {
        println("Writing object")

    private fun readObject(ois : ObjectInputStream) {
        println("Reading object")
        name = ois.readUTF()

Similarly, as above, readObject method must have precisely the signature:

private void readObject(ObjectInputStream stream)
    throws IOException, ClassNotFoundException;

as per Section 3.4.


    val car = Car("Ford")
    println("Serialized Car is a ${}")

    val byteArrayOutputStream = ByteArrayOutputStream()
    ObjectOutputStream(byteArrayOutputStream).use { oos ->

    val bytes = byteArrayOutputStream.toByteArray()

    val byteArrayInputStream = ByteArrayInputStream(bytes)
    ObjectInputStream(byteArrayInputStream).use {
        val newCar = it.readObject() as Car
        println("Deserialized Car is a ${}")

We then print to stdout:

Serialized Car is a Ford
Writing object
Reading object
Deserialized Car is a Ford

The simple repository can be found here.