Leon Leon - 27 days ago 18
Java Question

When is the static block of a class executed?

I have 2 jars lets call them a.jar and b.jar.

b.jar depends on a.jar.

in a.jar, I defined a class, lets 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 trigger jvm to load a class?

  3. how can I get the static block executed automatically?



Thanks

Answer

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.

Comments