Imaging you have the following to Java class with a static attribute
public class ClassWithStaticVariable
{
protected static int myNumber=0;
public static int getMyNumber()
{
return myNumber;
}
}
No you extend this class and want to initialize the static attribute of
your father in a static block (for whatever reason)
public class ClassWithStaticBlock extends ClassWithStaticVariable
{
static
{
myNumber=42;
}
public static void init() { };
}
It is obvious that if you just read the static variable of the father's
class the static init block never gets executed:
System.out.println(ClassWithStaticVariable.getMyNumber());
0
But how do you ensure it is executed? It seems to be a common practice
to execute the getName() method on the class attribute
ClassWithStaticBlock.class.getName();
System.out.println(ClassWithStaticVariable.getMyNumber());
Sadly, this stopped working after Java 1.4:
Result / Java Environment
42 / Java Vendor: Sun Microsystems Inc. Java version: 1.4.2_19 OS: x86 Windows Vista 6.1
0 / Java Vendor: Sun Microsystems Inc. Java version: 1.6.0_27 OS: x86 Windows 7 6.1
0 / Java Vendor: Oracle Corporation Java version: 1.7.0 OS: x86 Windows 7 6.1
So you better not trust static init blocks to be executed if you call
class.getName(). A reliable alternative might be to add an empty static
method to the class and call that method:
ClassWithStaticBlock.init();
This will trigger the static init block plus you can even add code to
the init method. Remember however, that this code maybe called more than
once, while your static init block normally is only executed once.