Pass argument to a static constructor in Java?

16.2k views Asked by At

I'm trying to initialize a static class, with an argument, and then run some more static code in that class.
I'm aware of the static block, but it seems it can't take any arguments.
Is there a way to pass arguments to a static constructor?
If not, what is the recommended technique to initialize a Static class using an argument?

Edit: A static class to my understanding is a class which cannot be instantiated (in c# they're called static classes, if Java has a different term for them, sorry for not being aware of it) - it's accessed through it's class name rather than an object name.

What I'm trying to achieve (very simplified) is a class which receives a dictionary as String, parses it, and has methods manipulate it like GetRandomEntry.

Here's an elaborated snippet of my code:

public class QuestionsRepository {  
private static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();  

//...  

staticĀ 
    {  
    // need to receive and parse dictionary here    
    }  
//...   

Taking the relevant parts of a code snippet is never easy, hope i have chosen wisely (:
Another detail that may be relevant - I'm a c# programmer, usually. Just Started learning Java lately.

Thanks.

6

There are 6 answers

4
James Jithin On BEST ANSWER

I think you would need to initialize the static fields of the class according to some input. You can do it in the following way by calling the static method of another class:

class ClassToInitialize {
    static {
        staticField = ParamPassClass.getParameter();
    }

    private static String staticField;

    ClassToInitialize() {
        System.out.println("This is the parameter: " + staticField);
    }

}

class ParamPassClass {
    private static String parameter;
    static String getParameter() {
        return parameter;
    }

    static void setParameter(String parameter) {
        ParamPassClass.parameter = parameter;
    }
}

class Main {
    public static void main(String args[]) {
        ParamPassClass.setParameter("Test param");
        new ClassToInitialize();
    }
}
0
Mark Rotteveel On

Java doesn't have static constructors. It only has static initializers and static initializers do not take any arguments. It is executed when the class is first loaded, and there is no way to call it yourself.

You either need to use actual objects, or add some way of configuring the class (eg through a static method).

1
Mark Bramnik On

you should mention the member class with a static qualifier, otherwise there is no such a thing as a static class Here you can find the explanation of using the word 'static' in this context.

Now you should just call its constructor and pass all the arguments you want, the only restriction that you have on a static member class is that it can't refer the non-static fields of its outer class, it resembles a static methods on class that can't refer the non-static fields of class.

I didn't understand why do you mention a static initialization block here, could you please clarify a little? Be aware also that in java there is no such a thing as static constructor....

Hope this helps

2
amit On

You can have a static method public static void setUp(Arg1 arg1, Arg2 arg2...) which sets up all your static fields and invoke it when your program starts.

You have to make sure this method will be called only once [or only when you want to reset these fields]

0
xea On

It is not possible to pass arguments directly to the static initializes (JLS:static initializers).

It would be nice if you could share more information about your goals.

0
Ted On

You could use an enum to initialize a singleton with a string parameter like this

import java.util.*;
class Data {
    static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();  
}
public enum QuestionsRepository
{
    repository("primary=red,green,blue;secondary=cyan,yellow,magenta"); 
    QuestionsRepository(String dictionary) {
        String[] rules = dictionary.split(";");
        for (String rule:rules) {
            String[] keyValuePair = rule.split("=",2);
            Data.easyDefinitions.put(keyValuePair[0],keyValuePair[1].split(","));
        }
    }
}