Pass a constructor argument to a static block

parameter passing in java with example
how to pass class object as parameter in java
passing object as parameter in java example
pass parameter to static constructor c#
java pass class type as parameter
java static initializer block hackerrank solution
static block in java
static block vs constructor

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

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();
    }

}

Passing Information to a Method or a Constructor (The Java , 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  Static Block vs. Constructor Static Block. In a Java class, a static block is a set of instructions that is run only once when a class is loaded into memory. A static block is also called a static

It's wrong to put that block of code in a static initializer block, since it depends on a constructor parameter, which is passed to the constructor after the static block is executed.

If that initialization depends on an instance specific parameter (different instances of CustomRestClient can receive different dbStrings), it should be moved to an instance method (i.e. not static).

On the other hand, if dbString should remain a static variable, it should be initialized by some static method, not the constructor. In that case, your static initializer block should be moved to that static method. It would be your responsibility to execute that static method.

How can we pass parameters to Static Constructors?, You can use any data type for a parameter of a method or a constructor. use a construct called varargs to pass an arbitrary number of values to a method. public class PassPrimitiveByValue { public static void main(String[] args) { int x = 3;  hi , My question is we can use static initialization block for having functionality like constructors for initializing static variable ,but we cannot pass arguments to static initialization block then how can I create functionality like parametrized constructors.Whats the alternative shall I use a static method to perform this functionality,since all methods in given class are static and there

That does not work because the static block runs during initialization of the class, before any instance is created or constructor runs.

And there is no way to pass parameters into that. The only thing it could do is load a static value from another place that you set up first. Reading from external configuration (system properties and such) is also an option.

You probably want to replace your static things with a singleton instance (with maybe a static method to initialize it) --- or even better a "regular" instance that you can then inject as a dependency into whatever code needs to use your CustomRestClient (that would make it easier if you ever need to work with multiple sets of connection settings).

Static blocks in Java, We can only pass parameter to a non static constructor(parametrized access any non-static member outside of a static method (constructor  Java static blocks will be called when JVM loads the class into memory, means it will be called only once. But constructor will be called everytime when you create an object. The below example can give you an idea about execution.

Passing Information into a Method or a Constructor, Unlike C++, Java supports a special block, called static block (also called static clause) which can the first time you access a static member of that class (even if you never make an object of that class). public static void main(String args[]) {​. In this code snippet I am going to tell you difference between static block and constructor in java by example. Static Block: Static block is a onetime execution block of java class. It executes automatically when JVM loads java class. It is useful to initialize static member's variables of class. Constructor: It is object level one time execution block. When JVM creates object for a class then constructor of that class execute once automatically.

Java - parameterized constructor with example, You can pass an argument of any data type into a method or a constructor. This includes public static Polygon polygonFrom(Point[] listOfPoints) { } The Java​  A class or struct can also have a static constructor, which initializes static members of the type. Static constructors are parameterless. If you don't provide a static constructor to initialize static fields, the C# compiler initializes static fields to their default value as listed in the Default values of C# types article.

Why Java Static Constructor is not allowed?, During object creation the parameters we pass, determine which constructor System.out.println("constructor with int and String param"); } public static void  In the above example, we initialize obj1 using a string. We then pass obj1 as an argument while creating obj2. Finally, when we print both object’s studentName variable using display function we get “Manan”. Calling Default Constructor From A Parameterized Constructor in Java

Comments
  • the static block runs before the constructor is executed. what you are trying to do isn't possible
  • Thank you for the explanation. Now, I have more idea on how static block works.
  • It should be pointed out that the final option is generally frowned upon. Since doing work, especially calling static methods, inside the constructor makes a class very hard to test.
  • @MattWatson yes, you can call a dedicated method instead after constructor