LearnFrenzy
Sign in Take a free test

Serialization · Serialization Programs · Question 7

Serialization-safe configuration with an enum in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Implement application configuration as an enum singleton with a settings map, serialize an object that holds a reference to it, and show that after loading the reference is still the one and only instance.

Solution
Main.java
import java.io.*;
import java.util.HashMap;
import java.util.Map;

enum AppConfig {
    INSTANCE;
    private final Map<String, String> settings = new HashMap<>(Map.of("theme", "dark"));
    String get(String k) { return settings.get(k); }
    void set(String k, String v) { settings.put(k, v); }
}

class Report implements Serializable {
    private static final long serialVersionUID = 1L;
    final String title;
    final AppConfig config;                   // reference to the singleton
    Report(String t, AppConfig c) { title = t; config = c; }
}

public class Main {
    static byte[] save(Object o) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(o);
        }
        return bytes.toByteArray();
    }

    static Object load(byte[] data) throws IOException, ClassNotFoundException {
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            return in.readObject();
        }
    }

    public static void main(String[] args) throws Exception {
        byte[] data = save(new Report("Q3 sales", AppConfig.INSTANCE));
        AppConfig.INSTANCE.set("theme", "light");
        Report back = (Report) load(data);
        System.out.println(back.title + " " + (back.config == AppConfig.INSTANCE) + " " + back.config.get("theme"));
    }
}

Output Verified by compiling and running

Q3 sales true light

Enum constants are written by name and resolved to the live constant, so references to the singleton stay correct without readResolve.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links