Java.Serialization.When should I change the value of the serialVersionUID field?

🧠 Purpose Recap: serialVersionUID

It’s used by Java to detect if the class used during deserialization is compatible with the class that was used during serialization.

If the serialVersionUID values differ → 💥 InvalidClassException

Continue reading →
Posted in Без рубрики | Comments Off on Java.Serialization.When should I change the value of the serialVersionUID field?

Java.Serialization.What is the role of the serialVersionUID field in serialization?

🧠 What is serialVersionUID?

serialVersionUID is a special static final long field that acts like a version number for a class.
It’s used to ensure that a serialized object can be deserialized correctly, even if the class has changed.

private static final long serialVersionUID = 1L;
Continue reading →
Posted in Без рубрики | Comments Off on Java.Serialization.What is the role of the serialVersionUID field in serialization?

Java.Serialization.How can I create my own serialization protocol?

✅ Example: Manual Serialization Protocol

🔹 Step 1: Define a class with custom writeTo() and readFrom() methods

import java.io.*;

public class User {
    private String username;
    private int age;

    public User(String username, int age) {
        this.username = username;
        this.age = age;
    }

    public void writeTo(DataOutputStream out) throws IOException {
        out.writeUTF(username);
        out.writeInt(age);
    }

    public static User readFrom(DataInputStream in) throws IOException {
        String username = in.readUTF();
        int age = in.readInt();
        return new User(username, age);
    }

    @Override
    public String toString() {
        return username + " (" + age + ")";
    }
}

🔹 Step 2: Save the object manually

try (DataOutputStream out = new DataOutputStream(new FileOutputStream("user.bin"))) {
    new User("Stanley", 33).writeTo(out);
}

🔹 Step 3: Load the object manually

try (DataInputStream in = new DataInputStream(new FileInputStream("user.bin"))) {
    User loaded = User.readFrom(in);
    System.out.println("Restored: " + loaded); // Restored: Stanley (33)
}

🔐 Bonus: Add encryption, compression, versioning

➕ Versioning

Add a version byte at the start:

out.writeByte(1); // version 1

Then during read:

int version = in.readByte();
if (version == 1) {
    // read fields...
}

➕ Encryption

Wrap your stream with a cipher stream:





CipherOutputStream cos = new CipherOutputStream(fos, myCipher);

➕ Compression

Wrap with GZIPOutputStream or DeflaterOutputStream.

🧠 Why Create Your Own Protocol?

ReasonBenefit
Full controlChoose format, compress, encrypt, etc.
Compact storageAvoid unnecessary metadata
Cross-language compatibilityWrite a format that works with Python, C++, etc.
Safe versioningHandle changes across versions easily
Avoid Java serialization quirksNo serialVersionUID, no reflection, no risk of accidental leaks

🧵 TL;DR

StepTool
Save object manuallywriteTo(DataOutput)
Load object manuallyreadFrom(DataInput)
Use custom formatsDataOutputStream, BufferedWriter, binary, JSON, etc.
Add versioningWrite a version byte at the start
Add securityWrap stream with Cipher, GZIP, etc.
Posted in Без рубрики | Comments Off on Java.Serialization.How can I create my own serialization protocol?

Java.Serialization.How can I prevent serialization?

🛑 1. Prevent Serialization of a Whole Class

Option A: Don’t implement Serializable

🚫 If a class doesn’t implement Serializable, it can’t be serialized.

public class NotSerializable {
    int x = 10;
}
Continue reading →
Posted in Без рубрики | Comments Off on Java.Serialization.How can I prevent serialization?

Java.Serialization.What effect do the static and final field modifiers have on serializability?

🔍 1. static Fields

✅ Summary:

static fields are never serialized.

Why?

  • static means the field belongs to the class itself, not to any specific object.
  • Serialization is all about saving the state of an object — and static fields are shared across all instances.

💡 So when you serialize an object, its static fields are ignored.

Continue reading →
Posted in Без рубрики | Comments Off on Java.Serialization.What effect do the static and final field modifiers have on serializability?

Java.Serialization.What does the transient keyword mean?

What does the transient keyword mean?

📘 Syntax

transient int secretCode;
Continue reading →
Posted in Без рубрики | Comments Off on Java.Serialization.What does the transient keyword mean?

Java.Serialization.How can I exclude fields from serialization?

🚫 Use the transient Keyword

When a field is marked as transient, Java skips it during serialization — it will not be written to the stream, and when deserialized, it will be set to its default value.

import java.io.*;

public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    String username;
    transient String password; // ❌ Do not serialize this

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
}

🔄 When deserialized:

User u = new User("Stanley", "mySecret123");
serializeToFile(u); // Save to file

User restored = deserializeFromFile(); // Load from file
System.out.println(restored.username); // "Stanley"
System.out.println(restored.password); // null ✅ because it was transient
Continue reading →
Posted in Без рубрики | Comments Off on Java.Serialization.How can I exclude fields from serialization?

Java.Serialization.CompressionExample

import java.io.*;
import java.util.zip.*;

public class CompressedPerson implements Serializable {
    private static final long serialVersionUID = 1L;

    private String name;
    private transient String bio; // a long text we want to compress

    public CompressedPerson(String name, String bio) {
        this.name = name;
        this.bio = bio;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject(); // serialize 'name'

        // Compress 'bio' and write it
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(byteOut);
        gzip.write(bio.getBytes("UTF-8"));
        gzip.close();
        byte[] compressed = byteOut.toByteArray();

        out.writeInt(compressed.length); // write length first
        out.write(compressed);           // write compressed bytes
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject(); // read 'name'

        // Read and decompress 'bio'
        int length = in.readInt();
        byte[] compressed = new byte[length];
        in.readFully(compressed);

        ByteArrayInputStream byteIn = new ByteArrayInputStream(compressed);
        GZIPInputStream gzip = new GZIPInputStream(byteIn);
        InputStreamReader reader = new InputStreamReader(gzip, "UTF-8");
        BufferedReader br = new BufferedReader(reader);

        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        this.bio = sb.toString().trim(); // restore 'bio'
    }

    public String getName() {
        return name;
    }

    public String getBio() {
        return bio;
    }
}
Continue reading →
Posted in Без рубрики | Comments Off on Java.Serialization.CompressionExample

Java.Serialization.How can I change the default serialization/deserialization behavior?

🔧 Ways to Customize Java Serialization

If your class implements Serializable, you can define two special methods:

private void writeObject(ObjectOutputStream out) throws IOException
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException

These allow you to manually control what gets written to and read from the stream.

Continue reading →
Posted in Без рубрики | Comments Off on Java.Serialization.How can I change the default serialization/deserialization behavior?

Java.Serialization.Describe the serialization/deserialization process using Serializable.

🔹 1. Mark the Class as Serializable

To make a class eligible for serialization:

import java.io.Serializable;

public class Person implements Serializable {
    private static final long serialVersionUID = 1L; // Optional but recommended

    String name;
    int age;

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

✅ This tells Java: “You can save and restore objects of this class.”

Continue reading →
Posted in Без рубрики | Comments Off on Java.Serialization.Describe the serialization/deserialization process using Serializable.