Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Constructor variable cannot be used

Tags:

java

I want to using the variable that already set in constructor but it return null.

Here is my code:

public class ServerConfig {

    private String ServerDbUrl;
    static String ServerDbUsername;
    static String ServerDbPassword;
    static String ServerDbName;
    private XMLConfiguration config; 

    public void  ServerConfig () {
        try {
            config = new XMLConfiguration(getClass().getResource("/config.xml"));
            // config.setExpressionEngine(new XPathExpressionEngine());

            //assign value;
            ServerDbUrl = config.getString("database.url");
            ServerDbUsername = config.getString("database.username");
            ServerDbPassword = config.getString("database.password");
            ServerDbName = config.getString("database.name");              
       } catch (Exception e) {
           System.out.println(e);
       }
    }

    public String GetServerDbUrl() {
        //return ServerDbUrl;
        return config.getString("database.url");
    }

On the function GetServerDbUrl(), either i want to get the ServerDbUrl or the config.getString() it would return null or error stack.

I know this short of newbie question, but I hope this would help another newbie like me in the future. any suggestion. Thanks.

like image 383
navotera Avatar asked Sep 18 '26 01:09

navotera


1 Answers

This is not a constructor, it's a regular method.

public void  ServerConfig ()

Therefore creating an instance of ServerConfig doesn't execute this method, and your instance variables remain uninitialized.

You should change the signature to :

public ServerConfig ()

A constructor doesn't have a return type.

like image 133
Eran Avatar answered Sep 19 '26 13:09

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!