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
Thanks
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With