Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sharing configuration between classess in the different packeges in Java

Let’s assume that I have 3 classes: JSONReader, Configuration, Worker.
With JSONReader I setting up the fields of Configuration.
With Worker I getting data of fields from Configuration.
So here the example of reader…

public class JSONReader {
    //Read json file and it's data...
    Configuration config = Configuration.getInstance();
    config.getInstance().setURISource(reader.get("uriSource"));
}

Here’s my configuration class

public class Configuration{
    private Configuration(){}
    private static Configuration instance = null;

    private final String uriSource;

    public static synchronized Configuration getInstance()
    {
        if (instance == null)
            instance = new Configuration();

        return instance;
    }

    public String setURISource(String uri){
        this.uriSource = uri;
    }

    public String getURISource(){
        return uriSource;
    }
}

Here the worker…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Worker {
    \\Doing some stuff, at certain point I need to get the data..
Connection connection = new Connection();    
connection.setConnection(Configuration.getInstance().getURISource()/*and other data*/);
}

I used the approach of singleton, verified the hashcode getting an instance of Configuration in my reader and worker…hashcodes returns the same value.
But, getters are null the same as variables are null after being set them in my reader.

Any suggestions? Ideas?

>Solution :

That’s because you are calling getInstance() twice.

config.getInstance().setURISource(reader.get("uriSource"));

Instead, you can directly do this:

config.setURISource(reader.get("uriSource"));

Also, variables mustn’t be final if you want to set them later.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading