When is the static block of a class executed?

Leon picture Leon · Feb 3, 2012 · Viewed 59.4k times · Source

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

Answer

ŁukaszBachman picture ŁukaszBachman · Feb 3, 2012

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.