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

🧠 Why Use transient?

Field TypeReason to Exclude
Passwords / API Keys🛡 Security
Cache / derived values♻ Can be rebuilt, don’t waste space
Database connections / threads🔌 Can’t be serialized
Large fields not needed after restart💾 Save space

⚠️ What Happens to Transient Fields?

Field TypeDeserialized Value
Stringnull
int, long, double, etc.0
booleanfalse
Objectnull

You can rebuild or initialize them in:

  • readObject() method
  • A custom constructor or init method

🧵 TL;DR

FeatureUsage
Exclude field from serializationtransient keyword
Default value after deserializationYes
Used forSensitive, non-serializable, or unnecessary data
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.