javaconstructorstaticstatic-block

Pass a constructor argument to a static block


I have a class like this

public class CustomRestClient {

private static String dbString;

public CustomRestClient(String db) {
    this.dbString = db;
}

static {       
    try {
        Client.setServer(Client.Server.LOCAL);
        AuthenticationProvider provider = new AuthenticationProvider();
        provider.setCredentialsProvider(new SimpleCredentialsProvider("user", "pass", dbString, "secretkey"));
        Client.setAuthenticationProvider(provider);
        Client.login();
    } catch (ClientException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    CustomRestClient customRestClient = new CustomRestClient("db");
 }
}

I'm trying to pass the constructor argument inside the static block

provider.setCredentialsProvider(new SimpleCredentialsProvider("user", "pass", dbString, "secretkey"));

For example, CustomRestClient customRestClient = new CustomRestClient("db"); should set the dbString field inside the static block to db. But when I run the program it says the dbString field is null. I have no idea what I'm doing wrong


Solution

  • static block is executed before you create the CustomRestClient object

    You should move the static block to static method and call it

    public static void login(String db) {
            Client.setServer(Client.Server.LOCAL);
            AuthenticationProvider provider = new AuthenticationProvider();
            provider.setCredentialsProvider(new SimpleCredentialsProvider("user", "pass", dbString, "secretkey"));
            Client.setAuthenticationProvider(provider);
            Client.login();
    }
    

    And call it:

    CustomRestClient.login("db")
    

    Or (without static) move the method inside a constructor with String argument

    private String dbString;
    
    public CustomRestClient(String db) {
        this.dbString = db;
        try {
            Client.setServer(Client.Server.LOCAL);
            AuthenticationProvider provider = new AuthenticationProvider();
            provider.setCredentialsProvider(new SimpleCredentialsProvider("user", "pass", dbString, "secretkey"));
            Client.setAuthenticationProvider(provider);
            Client.login();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    

    }