When is the static block of a class executed?
Yes, you are right. Static initialization blocks are run when the JVM (class loader - to be specific) loads StaticClass
(which occurs the first time it is referenced in code).
You could force this method to be invoked by explicitly calling StaticClass.init()
which is preferable to relying on the JVM.
You could also try using Class.forName(String)
to force the JVM to load the class and invoke its static blocks.
First of all class loading is different than class initialization. For anyone looking for explanation from Java Language Specification, when is static block executed - here it is.
The JLS §8.7 says that :
A static initializer declared in a class is executed when the class is initialized (§12.4.2).
So what does the initialization mean? Let's refer to JLS §12.4.2. This describes detailed initialization procedure. However point JLS §12.4.1 might be more appropriate here. It says that :
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:T is a class and an instance of T is created. T is a class and a static method declared by T is invoked. A static field declared by T is assigned. A static field declared by T is used and the field is not a constant variable (§4.12.4). T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
So to make the static initializer block to be executed automatically, you have to force one of those options to happen.
Yes you are right, since you are not using your StaticClass
it is not loaded by the vm and therefore init()
is never executed.
For your second question, you probably have to go the hard way and scan all available classes and load them.
https://stackoverflow.com/a/3223019/393657