Serialization in Java Tutorial with Examples

11 months ago 44

Serialization is simply a cardinal conception successful Java programming that allows objects to beryllium converted into a format suitable for retention oregon transmission. It plays a important relation successful tasks specified arsenic persisting entity state, sending objects implicit a network, oregon adjacent for caching purposes. In this article, we volition delve into the satellite of Java serialization, exploring its mechanics, usage cases, champion practices and imaginable pitfalls.

What is serialization?

Serialization is the process of converting an entity into a format that tin beryllium easy stored, transmitted oregon reconstructed later. Serialization is peculiarly utile erstwhile you request to prevention the authorities of an entity to disk, nonstop it implicit a web oregon walk it betwixt antithetic parts of a program.

Java employs its ain binary serialization watercourse protocol. Serialization is achieved done a operation of the ObjectOutputStream and ObjectInputStream classes, and the implementation of marker interfaces Serializable and Externalizable.

See Also: Java directory navigation

How serialization works successful Java

ObjectOutput/InputStream

The halfway of Java serialization lies successful the ObjectOutputStream and ObjectInputStream classes. These streams supply methods to constitute and work objects. Here’s a elemental illustration of serializing an object:

// Serialization try (ObjectOutputStream retired = caller ObjectOutputStream(new FileOutputStream("data.dat"))) {   MyClass obj = caller MyClass("John Doe", 25);   out.writeObject(obj); } drawback (IOException e) { e.printStackTrace(); } // Deserialization try (ObjectInputStream successful = caller ObjectInputStream(new FileInputStream("data.dat"))) { MyClass obj = (MyClass) in.readObject(); System.out.println(obj.getName()); // Outputs: John Doe } drawback (IOException | ClassNotFoundException e) { e.printStackTrace(); }

Serializable interface

To alteration serialization, a people indispensable instrumentality the Serializable interface. This is known arsenic a marker interface, meaning it doesn’t person immoderate methods, but it serves arsenic a emblem to the Java Virtual Machine that the people tin beryllium serialized. If a people doesn’t instrumentality Serializable and you effort to serialize an lawsuit of it, a java.io.NotSerializableException volition beryllium thrown.

import java.io.Serializable; public people MyClass implements Serializable { backstage String name; backstage int age; // Constructor, getters, setters, etc. }

Externalizable interface

In summation to Serializable, Java provides the Externalizable interface. Unlike Serializable, which handles serialization automatically, Externalizable allows you to person implicit power implicit the serialization process by implementing 2 methods: writeExternal and readExternal.

import java.io.Externalizable; import java.io.ObjectOutput; import java.io.ObjectInput; import java.io.IOException; public people MyExternalizableClass implements Externalizable { backstage String name; backstage int age; // Constructor, getters, setters, etc. @Override nationalist void writeExternal(ObjectOutput out) throws IOException { out.writeObject(name); out.writeInt(age); } @Override nationalist void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { sanction = (String) in.readObject(); property = in.readInt(); } }

Serialization and entity graphs

When you serialize an object, it’s important to enactment that the full entity graph is serialized. This means that if your entity contains references to different objects, those volition beryllium serialized arsenic well. This tin pb to unexpected behaviour if the referenced objects aren’t themselves serializable.

public people Person implements Serializable { backstage String name; backstage Address address; // Constructor, getters, setters, etc. } public people Address { backstage String street; backstage String city; // Constructor, getters, setters, etc. }

In this example, if Address doesn’t instrumentality Serializable, a java.io.NotSerializableException volition beryllium thrown erstwhile trying to serialize a Person object.

See Also: Top Java IDEs and Code Editors

Customizing serialization

Controlling serialization with writeObject() and readObject()

Sometimes, you whitethorn request much power implicit the serialization process. This tin beryllium achieved by implementing writeObject() and readObject() methods successful your class. These methods are called during serialization and deserialization, allowing you to specify customized behavior.

private void writeObject(ObjectOutputStream out) throws IOException { // Custom serialization codification here } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // Custom deserialization codification here }

Using writeReplace() and readResolve()

The writeReplace() and readResolve() methods supply different level of customization. They let you to specify alternate objects to beryllium utilized during serialization and deserialization. This is often utilized to guarantee that a singleton people remains a singleton aft deserialization.

private Object writeReplace() throws ObjectStreamException { instrumentality someReplacementObject; } private Object readResolve() throws ObjectStreamException { instrumentality someActualObject; }

Versioning and compatibility

As your exertion evolves, truthful bash your classes. It’s important to see versioning erstwhile dealing with serialized objects. This is to guarantee that older versions of your exertion tin inactive deserialize objects saved by newer versions and vice versa.

This tin beryllium achieved by providing a serialVersionUID tract successful your class. This tract is simply a unsocial identifier for the people and should beryllium updated whenever the people is modified successful a mode that affects serialization compatibility.

private static last agelong serialVersionUID = 1L;

Security considerations

Serialization and deserialization tin present information risks, particularly erstwhile dealing with untrusted data. It’s recommended to validate input and see utilizing techniques specified arsenic entity filtering oregon utilizing a whitelist of allowed classes during deserialization.

Performance implications

While serialization is simply a convenient mode to persist entity state, it tin person show overhead, particularly for ample entity graphs. Consider utilizing alternate serialization libraries specified arsenic Kryo oregon Protocol Buffers if show is simply a captious concern.

Common pitfalls and champion practices

  • Forgetting to instrumentality serializable: This is simply a communal mistake, truthful ever guarantee that immoderate people you mean to serialize implements the Serializable interface.
  • Not handling entity graphs: Be alert that erstwhile you serialize an object, its full entity graph is serialized, truthful marque definite each objects successful the graph are serializable.
  • Versioning: Keep way of serialVersionUID and update it appropriately erstwhile making changes to serialized classes.

Alternative serialization libraries

While Java’s built-in serialization mechanics is powerful, it whitethorn not ever beryllium the astir businesslike option. Consider exploring libraries specified arsenic Kryo, Protocol Buffers oregon Jackson for much specialized usage cases.

Final thoughts connected serialization successful Java

Java serialization is simply a versatile instrumentality that enables the persistence and transmission of entity state. By knowing the mechanics, customization options, versioning and information considerations, you tin efficaciously leverage serialization successful your applications. Remember to ever support show successful caput and see alternate serialization libraries for circumstantial usage cases. With these skills successful hand, you’ll beryllium well-equipped to grip a wide scope of tasks involving entity serialization successful Java.

Featured Partners

1 Zoho Assist

Zoho Assist

Visit website

With Zoho Assist File transfer, you tin nonstop and person files and folders during your distant sessions. Effortlessly transportation and negociate files arsenic ample arsenic 5 GB successful size with nary maximum bounds for a azygous transfer. Files of each formats tin beryllium shared without dependence connected intermediate storage, similar USBs oregon cloud-based retention devices, keeping your workflow uninterrupted and your information protected.

Learn much astir Zoho Assist

Read Entire Article