get static initialization block to run in a java without loading the class

randomThought picture randomThought · Apr 6, 2010 · Viewed 9.3k times · Source

I have a few classes as shown here

public class TrueFalseQuestion implements Question{
    static{
        QuestionFactory.registerType("TrueFalse", "Question");
    }
    public TrueFalseQuestion(){}
}

...

public class QuestionFactory {

 static final HashMap<String, String > map =  new HashMap<String,String>();

 public static void registerType(String questionName, String ques ) {
     map.put(questionName, ques);
     }
 }



public class FactoryTester {
    public static void main(String[] args) {
        System.out.println(QuestionFactory.map.size());
        // This prints 0. I want it to print 1
    }
}

How can I change TrueFalseQuestion class so that the static method is always run so that I get 1 instead of 0 when I run my main method? I do not want any change in the main method.

I am actually trying to implement the factory patterns where the subclasses register with the factory but i have simplified the code for this question.

Answer

Bozho picture Bozho · Apr 6, 2010

You can call:

Class.forName("yourpackage.TrueFalseQuestion");

this will load the class without you actually touching it, and will execute the static initializer block.