get static initialization block to run in a java without loading the class
Posted
by TP
on Stack Overflow
See other posts from Stack Overflow
or by TP
Published on 2010-04-06T05:46:47Z
Indexed on
2010/04/06
5:53 UTC
Read the original article
Hit count: 290
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 Type 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.
© Stack Overflow or respective owner