Skip to main content

How to serialize a class with static variables in Java




TL;DR

You can't!

Instead;
Change the static variables into a none static member variable of a singleton class. By making the variables holding class to a singleton, still, it caters to the requirement of keeping your variables having a single reference for the entire application. (This is one of the ways of doing it, surely there are more other elegant ways and crude hacks of doing this depending on the situation)


This is a problem that a scholar asked me for some help with.

We have a simple use case where there's a configuration class that it requires to hold some values used in application-wide. So the easiest way (not the best) somebody could think would be making the variables static, so it would be only a single reference for it throughout the whole application.

Let's imagine the configuration class would look like below.

import java.io.Serializable;

public class BranchConfig implements Serializable{
    
    private static String branchName;
    private static String branchAddress;

    public static String getBranchName() {
        return branchName;
    }

    public static void setBranchName(String branchName) {
        BranchConfig.branchName = branchName;
    }

    public static String getBranchAddress() {
        return branchAddress;
    }

    public static void setBranchAddress(String branchAddress) {
        BranchConfig.branchAddress = branchAddress;
    }
}

Note that, it has implemented the Serializable interface to make it for serialization.
Now, we would try to serialize this and write it into a file in a separate class.
To display this, we have tried this in the main method as below.


import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        BranchConfig branchConfig = new BranchConfig();
        branchConfig.setBranchAddress("Kandy");

        //serializing and writing into a file
        ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream("branch.data"));
        objectOut.writeObject(branchConfig);
        objectOut.close();

        //setting the value null just to make whether we read it from the file below
        BranchConfig.setBranchAddress(null);

        //Reading from the file
        ObjectInputStream objectinputstream = new ObjectInputStream(new FileInputStream("branch.data"));
        BranchConfig configFromFile = (BranchConfig) objectinputstream.readObject();
        System.out.println(configFromFile.getBranchAddress());
    }
}


And, you guessed right, it writes something to a file, but when you read it, the static values are null.

There can be a number of elegant ways to fix this and some crude hacks also, but I like using the Singleton design pattern to fix this issue.

By making a class a singleton, we can make sure there is one and the only instance of this class ever could be created. Therefore it secures the requirement of having a single reference for the config variables that we need for the entire application.

Following is the singleton version of this class


import java.io.Serializable;

public class BranchConfig implements Serializable{

    private String branchName;
    private String branchAddress;

    //instantiate as a static member
    private static BranchConfig instance = new BranchConfig();

    //private to make sure nobody else can create instances of this class
    private BranchConfig() {
    }

    public String getBranchName() {
        return branchName;
    }

    public void setBranchName(String branchName) {
        this.branchName = branchName;
    }

    public String getBranchAddress() {
        return branchAddress;
    }

    public void setBranchAddress(String branchAddress) {
        this.branchAddress = branchAddress;
    }

    public static BranchConfig getInstance(){
        return instance;
    }
}

To support this, the Main class was changed as below.

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        BranchConfig branchConfig = BranchConfig.getInstance();
        branchConfig.setBranchAddress("Kandy");

        //serializing and writing into a file
        ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream("branch.data"));
        objectOut.writeObject(branchConfig);
        objectOut.close();

        //setting the value null just to make whether we read it from the file below
        branchConfig.setBranchAddress(null);

        //Reading from the file
        ObjectInputStream objectinputstream = new ObjectInputStream(new FileInputStream("branch.data"));
        BranchConfig configFromFile = (BranchConfig) objectinputstream.readObject();
        System.out.println(configFromFile.getBranchAddress());
    }
}


Now, we were able to properly serialize and deserialize the configs.

But, it looks like we violated our first requirement of having a single reference for the config data once again. If you see, there is another object created from the deserializing file data.

To fix this, we'll have to disable serialization of the config class. So nobody else can create objects from deserialization. Then how can we save them into the file? We can create a private file inside the Config to read/write from the file which is again serializable.

Here's the new BranchConfig file with that modification.

import java.io.*;

public class BranchConfig {

    private static class Data implements Serializable {
        public String branchName;
        public String branchAddress;
    }

    private static Data data = new Data();

    //instantiate as a static member
    private static BranchConfig instance = new BranchConfig();

    //private to make sure nobody else can create instances of this class
    private BranchConfig() {
    }

    public String getBranchName() {
        return data.branchName;
    }

    public void setBranchName(String branchName) {
        data.branchName = branchName;
    }

    public String getBranchAddress() {
        return data.branchAddress;
    }

    public void setBranchAddress(String branchAddress) {
        data.branchAddress = branchAddress;
    }

    public static BranchConfig getInstance(){
        return instance;
    }

    public static void saveConfig() throws IOException {
        //serializing and writing into a file
        ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream("branch.data"));
        objectOut.writeObject(data);
        objectOut.close();
    }

    public static void openConfig() throws IOException, ClassNotFoundException {
        //Reading from the file
        ObjectInputStream objectinputstream = new ObjectInputStream(new FileInputStream("branch.data"));
        data = (Data) objectinputstream.readObject();
    }
}

Here, we have getters and setters to encapsulate the actual config values that resides in the Data instance.

The Main class to use this code would be like follows.


import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        BranchConfig branchConfig = BranchConfig.getInstance();
        branchConfig.setBranchAddress("Kandy");

        //serializing and writing into a file
        BranchConfig.saveConfig();

        //setting the value null just to make whether we read it from the file below
        branchConfig.setBranchAddress(null);

        //Reading from the file
        BranchConfig.openConfig();

        System.out.println(BranchConfig.getInstance().getBranchAddress());
    }
}


This makes sure the config data can be serialized into a file and nobody else can create config data from outside the config class. Thus, a single reference to config data is maintained.

This can be further improved based on your needs. For example, the singleton behavior of the Config class can be also changed since we already have a single reference covered with the static data instance inside it.

Of course, there are more elegant ways of doing that. Rather than using conventional serialization, we can use a JSON object mapper to read/write data from a file, which would be more human-readable also.



Comments

Popular posts from this blog

Install Docker on Windows 11 with WSL Ubuntu 22.04

This is to install Docker within Ubuntu WSL without using the Windows Docker application. Follow the below steps. Install Ubuntu 22.04 WSL 1. Enable Windows Subsystem for Linux and Virtual Machine platform Go to Control Panel -> Programs -> Programs and Features -> Turn Windows features on or off 2. Switch to WSL 2 Open Powershell and type in the below command. wsl --set-default-version 2 If you don't have WSL 2, download the latest WSL 2 package and install it.  3. Install Ubuntu Open Microsoft Store and search for Ubuntu. Select the version you intend to install. I'd use the latest LTS version Ubuntu 22.04. Click on the Get button. It will take a couple of minutes to download and install. 4. Open up the installed Ubuntu version that was installed. If you get an error like the below image, make sure to install the WSL2 Kernel update .  If it's an older Ubuntu version the error message would be something like the image below. Error: WSL 2 requires an update to its ...

How to fix SSLHandshakeException PKIX path building failed in Java

TL ; DR 1. Extract the public certificate of the website/API that you are trying to connect from your Java application. Steps are mentioned in this post 2. Use the Java keytool to install the extracted certificate into the "cacerts" file (Trust store) keytool -import -trustcacerts -alias <domain name> -file <public certificate>.cert -keystore /path_to_java_home/jre/lib/security/cacerts -storepass changeit 3. Restart your Java application Exception A typical exception stack trace would look like below. javax.net.ssl. SSLHandshakeException : sun.security.validator.ValidatorException: PKIX path building failed : sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1959) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302) at sun.security.ssl.Handshake...

Automatically open Chrome developer tools in a new tab

Sometimes we need to check the console or the network transactions of a link that opens up in a new tab. By default, the Chrome developer tools are not opening in a new tab. So, by the time when we hit F12 and open the dev tools, part of the information we needed could be already gone.  There's a setting in dev tools where you can keep the dev tools open automatically in a new tab. To enable that, hit F12 and open up the dev tools. Click on the settings icon in the top right corner. In the Preferences section, scroll down to the bottom. You'll be able to find the option to Auto-open DevTools for popups. Select the checkbox and we're good to go!