When is the static block of a class executed?

Solution 1:

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.

Solution 2:

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