Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Java object serialization to a byte array

Write an object to a `byte[]` and reconstruct it from trusted bytes generated by the same program. See why default serialization omits `transient` fields.

Version: Java SE 21

Syntax

Java SE 21 — java.io
ByteArrayOutputStream()
ObjectOutputStream(OutputStream out) throws IOException
void ObjectOutputStream.writeObject(Object obj) throws IOException
void ObjectOutputStream.flush() throws IOException
byte[] ByteArrayOutputStream.toByteArray()
ByteArrayInputStream(byte[] buf)
ObjectInputStream(InputStream in) throws IOException
Object ObjectInputStream.readObject() throws IOException, ClassNotFoundException

In Java SE 21, the java.io classes let you write and reconstruct an object entirely in memory. The ObjectOutputStream constructor writes the stream header. ObjectOutputStream.writeObject/flush refers to two separate calls: writeObject(Object) serializes the object and the graph reachable through references being serialized; flush() sends buffered bytes to the underlying stream without closing it. The Object parameter does not guarantee success: an object being serialized that does not implement Serializable can cause NotSerializableException.

After writing and flushing, use ByteArrayOutputStream.toByteArray (called as buffer.toByteArray()) to get a new byte[] containing a copy of just the bytes written. It neither exposes the internal buffer nor flushes the object stream. ByteArrayInputStream(byte[]) uses that array without copying it.

The ObjectInputStream constructor reads the header. readObject() reconstructs the object and returns it as Object; the cast to Profile checks the expected type only after deserialization. Read successive values in the same order and with the corresponding types used when writing them. Stream operations can throw IOException; reading can also throw ClassNotFoundException if a required class is unavailable. The try-with-resources blocks close the object streams.

Default serialization omits static and transient fields. When an ordinary serializable class is reconstructed, its constructor and field initializers do not run, so cache has its type's default value, null, rather than warm. Where serialVersionUID matching is required, a mismatch causes InvalidClassException. Array and record classes are exempt from the matching requirement. A matching ID does not make arbitrary class changes compatible. This is not a language-independent interchange format. Do not deserialize untrusted data: the example reads only bytes generated locally by the same program.

Examples

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serial;
import java.io.Serializable;

public class SerializationRoundTrip {
    private static final class Profile implements Serializable {
        @Serial
        private static final long serialVersionUID = 1L;

        private final String name;
        private transient String cache = "warm";

        private Profile(String name) {
            this.name = name;
        }
    }

    public static void main(String[] args)
            throws IOException, ClassNotFoundException {
        Profile original = new Profile("Ada");
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] bytes;
        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {
            out.writeObject(original);
            out.flush();
            bytes = buffer.toByteArray();
        }

        Profile restored;
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
            restored = (Profile) in.readObject();
        }

        System.out.println("before: " + original.name + ", cache=" + original.cache);
        System.out.println("after: " + restored.name + ", cache=" + restored.cache);
    }
}

Result

before: Ada, cache=warm
after: Ada, cache=null

Compare `before` and `after`: `name` remains `Ada`, but `cache` is `warm` in the original and `null` in the reconstructed object.

Related lessons

  • Java · Lesson 52 · Advanced · Version: 2

Sources