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")
        oos.writeUTF(name)
    }

    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.

Then:

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

    val byteArrayOutputStream = ByteArrayOutputStream()
    ObjectOutputStream(byteArrayOutputStream).use { oos ->
        oos.writeObject(car)
        oos.flush()
    }
    byteArrayOutputStream.flush()

    val bytes = byteArrayOutputStream.toByteArray()
    byteArrayOutputStream.close()

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

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.