Pass argument to a static constructor in Java?

Oren A picture Oren A · Jan 29, 2012 · Viewed 14.7k times · Source

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.

Answer

James Jithin picture James Jithin · Jan 29, 2012

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