Java custom serialization example

Java Custom Serialization — Complete Guide With Example 

(Updated with transient vs non-transient fields explanation)

Serialization is a core concept in Java and plays a major role in distributed systems, microservices, caching, and message passing.
This blog explains:

  • What serialization is

  • Why serialization is needed

  • What transient & non-transient mean

  • How custom serialization works

  • Real-world use cases

  • Complete code example


1. What Is Serialization in Java?

Serialization is the process of converting an object into a byte stream so it can be:

✔ Stored in a file
✔ Sent over a network
✔ Stored in cache
✔ Persisted temporarily
✔ Shared between JVM instances

Java provides built-in serialization with:

implements Serializable

2. Why Serialization Is Needed (Real Use Cases)

Serialization is crucial in many systems:

✔ Distributed Systems

Send objects between services (legacy RMI, microservices, RPC frameworks).

✔ Caching

Store Java objects in Redis, Hazelcast, Ignite.

✔ Message Passing

Kafka, ActiveMQ, RabbitMQ often serialize objects.

✔ File/Session Storage

Store state so it can be restored later.


3. What Are Transient and Non-Transient Fields?

Serialization by default saves every non-transient field of a class.

But sometimes we do NOT want all fields to be serialized.

📍 Transient Field

A transient field is NOT serialized even if the class implements Serializable.

Example:

transient String password;

Java intentionally skips this during serialization.

📍 Non-Transient Field

Normal variables (without transient) are serialized.

Example:

String name; // serialized int age; // serialized

4. Why Java Introduced transient?

(Why do we need it?)

✔ 1. Security

You don’t want to serialize sensitive data:

  • passwords

  • tokens

  • API keys

  • cryptographic secrets

✔ 2. Derived (non-essential) fields

Some fields can be computed again at runtime.

transient int cachedHashCode;

✔ 3. Large fields not needed in serialization

Example: temporary buffers

✔ 4. Prevent unwanted state transfer

Ex: open network connections, thread objects, file streams

These objects cannot be serialized, so marking them transient avoids errors.

✔ 5. Reduce payload

Skipping unnecessary fields reduces storage & network cost.


5. How transient Works Internally?

When serializing:

  • JVM examines all fields

  • If a field is transient → it is skipped

  • If not transient → JVM serializes it

On deserialization:

  • Transient fields are restored as default values:

    • 0 for numbers

    • false for boolean

    • null for all objects


6. Custom Serialization (writeObject & readObject)

Sometimes we need even more control, beyond transient.

Example use case:

Do not serialize Employee object IF address is empty.

For such rules, Java lets you override serialization using:

private void writeObject(ObjectOutputStream out) private void readObject(ObjectInputStream in)

7. Full Example: Custom Serialization in Java

🟦 Employee class

class Employee implements Serializable { private static final long serialVersionUID = 5845255930677343859L; private String name; private String address; public Employee(String name, String address) { this.name = name; this.address = address; } private void writeObject(ObjectOutputStream o) throws IOException { if (address == null || address.length() == 0) { throw new IllegalArgumentException(); } o.writeObject(name); o.writeObject(address); } private void readObject(ObjectInputStream o) throws IOException, ClassNotFoundException { name = (String) o.readObject(); address = (String) o.readObject(); } @Override public String toString() { return "Employee [name=" + name + ", address=" + address + "]"; } }

🟧 Main Class

public class CustomSerializaionExample { public static void main(String[] args) { Employee emp = new Employee("Vinod", ""); try { FileOutputStream fos = new FileOutputStream("employee.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(emp); // calls custom writeObject() oos.close(); FileInputStream fis = new FileInputStream("employee.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Employee deemp = (Employee) ois.readObject(); ois.close(); System.out.println(deemp); } catch (Exception e) { e.printStackTrace(); } } }

8. Expected Output

Exception in thread "main" java.lang.IllegalArgumentException at Employee.writeObject(...)

This shows that your custom validation logic executed.

Since address is empty, the object is blocked from serialization.


9. Where Transient + Custom Serialization Are Useful

ScenarioUse CaseFeature
Sensitive fieldsPassword, token, keytransient
Skip invalid objectsMissing mandatory datawriteObject()
Reduce sizeRemove large bufferstransient
Derived fieldsRecalculate instead of storingtransient
Full control over serializationBusiness validationwriteObject/readObject

Often you combine both transient and custom serialization.


10. Summary

✔ Serialization converts an object to bytes

✔ Needed for networking, caching, persistence

transient prevents sensitive/unwanted fields from being serialized

✔ Custom writeObject() allows full control over what & how to serialize

✔ Your example shows validation-based serialization control

✔ Very useful in secure, distributed, or performance-critical systems


No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts