javajvminitializationclassloaderstatic-block

When is the static block of a class executed?


I have 2 jars, let's call them a.jar and b.jar.

b.jar depends on a.jar.

In a.jar, I defined a class, let's call it StaticClass. In the StaticClass, I defined a static block, calling a method named "init" :

public class StaticClass {
  static {
    init();
  } 

  public void static init () {
    // do some initialization here
  }
}

in b.jar, I have a main, so in the main, I expect that the init() method has been called, but actually not. I suspect that is because the StaticClass has not been loaded by the jvm, could anyone tell me

  1. Is my conclusion correct?
  2. What triggers the jvm to load a class?
  3. How can I get the static block executed automatically?

Thanks


Solution

  • 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.