Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 980
Leon Avatar asked Feb 03 '12 14:02

Leon


People also ask

When the static block is executed?

A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.

Is static block executed before Main?

Static Block and main() method in Java In Java static block is used to initialize the static data members. Important point to note is that static block is executed before the main method at the time of class loading.

Is static block executed only once?

Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class. This code inside the static block is executed only once: the first time the class is loaded into memory.

Is static block executed before constructor?

Order of execution When you have all the three in one class, the static blocks are executed first, followed by constructors and then the instance methods.


1 Answers

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.

like image 178
ŁukaszBachman Avatar answered Sep 25 '22 02:09

ŁukaszBachman