Serialization
What is serialization?
- Serialization: object → bytes (to save in a file or send over a network).
- Deserialization: bytes → object.
Making a class serializable
import java.io.Serializable;
public class Player implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int level;
private transient String sessionToken; // NOT saved
}
Serializableis a marker interface: it has no methods. It just says "this is allowed".transientfields are skipped. Use it for passwords, tokens, caches.serialVersionUIDis a version number. If the class changes and the number doesn't match the saved data, loading fails withInvalidClassException.- Every field's type must also be serializable (or
transient).
Writing and reading
try (var out = new ObjectOutputStream(Files.newOutputStream(Path.of("save.dat")))) {
out.writeObject(player);
}
try (var in = new ObjectInputStream(Files.newInputStream(Path.of("save.dat")))) {
Player loaded = (Player) in.readObject();
}
⚠️ Security warning
Never deserialize data from untrusted sources (user uploads, the internet). Crafted bytes can run harmful code inside your app.
Modern alternative: JSON
Most apps today save data as JSON using libraries like Jackson or Gson. It's human-readable, works with any language, and is safer. Your Supabase database already talks JSON!
Example
import java.io.*;
import java.nio.file.*;
class Player implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int level;
transient String password;
Player(String name, int level, String password) {
this.name = name; this.level = level; this.password = password;
}
}
public class SaveGame {
public static void main(String[] args) throws Exception {
Path file = Path.of("save.dat");
try (var out = new ObjectOutputStream(Files.newOutputStream(file))) {
out.writeObject(new Player("Javi", 7, "secret"));
}
try (var in = new ObjectInputStream(Files.newInputStream(file))) {
Player p = (Player) in.readObject();
System.out.println(p.name + " lvl " + p.level); // Javi lvl 7
System.out.println(p.password); // null (transient)
}
}
}