πŸ•―οΈ Java Serialisation & Deserialisation

GunhoΒ·2025λ…„ 1μ›” 22일

πŸ•―οΈ Java Serialisation & Deserialisation

πŸ•―οΈ Java Serialisation is a process of transforming a Java Object into a byte stream while Java Deserialisation is vice versa, the process of transforming byte stream into a Java Object.

Java Serialisation is often used to store objects into a database, file, or memory or to send objects to a different VM via networks.

Transforming objects into JSON and XML can also be considered a Serialisation.

Geeks for Geeks Available here


πŸ“ Serialisation & Deserialisation in Practice

In Java, Serialisation can be implemented via Serializable Interface, a marker interface without any public APIs.

Serializable Interface

public interface Serializable {
}

Once a class implements the Serializable Interface, its serialVersionUID can be explicitly defined to identify a unique object version for its compatibilities across different platforms.

Finally, with the ObjectOutputStream, combined with any OutputStream sub classes, Java will execute the serialisation:

Person Class

class Person implements Serializable {
	private static final long serialVersionUID = 1L;
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Serialisation

class Example {
	
    public static void main() {
    	Person person = new Person("A", 20);
        
        try (ObjectOutputStream oos = new ObjectOutputStream(FileOutputStream("person.txt")) {
        	oos.writeObject(person);
        } catch(IOException e) {
        	e.printStackTrace();
        }
    }
}

Similarly, deserialisation can be performed via ObjectInputStream, combined with any InputStream sub classes:

Deserialisation

class Example {
	
    public static void main() {
    	Person person = new Person("A", 20);
        
        try (ObjectInputStream ois = new ObjectInputStream(FileInputStream("person.txt")) {
        	(Person) dePerson = oos.readObject(person);
        } catch(IOException e) {
        	e.printStackTrace();
        }
    }
}

🧯 Limitations with Serialisation & Deserialisation

Some notable issues with conventional Java Serialisation & Deserialisation is potential byte manipulations that could change the value of the entire objects.

Hence, for security related concerns, it is often adviced to explicitly define serialVersionUID and to write custom readObject() method to further validate the deserialised objects.

Other notable limitation is with Java Serialisation & Deserialisation being an exclusive feature only available in Java environments. Hence, recently, data serialisation formats such as JSON, XML, Protocol Buffers, and Avro appear to be often used in practices as these formats happen to be language-independent.


πŸ“š References

μš°μ•„ν•œ ν…Œν¬ μ½”μŠ€
F-Lab
Geeks for Geeks

profile
Hello

0개의 λŒ“κΈ€