0

I was under the impression that a class's static initialization block gets called when the class is loaded.

(For example see this answer: https://stackoverflow.com/a/9130560/889742 )

But this test shows that the static block is not called at class load time, but later at first use time.

Why?

class Test
{
    static
    {
        System.out.println("In test static block");
    }
    static int x;
}

public class xxxx {

    public static void main(String[] args) throws Exception {
        Class<?> clasz = ClassLoader.getSystemClassLoader().loadClass("Test");
        //at least one of these lines is required for static block to be called
        //Test.x = 1;  
        //clasz.newInstance();
    }

}
Gonen I
  • 5,576
  • 1
  • 29
  • 60
  • *But this test shows that the static block is not called at class load time, but later at first use time.* - because your understanding was incorrect? – Scary Wombat Oct 03 '18 at 07:15
  • Java Language Specification: "A static initializer declared in a class is executed when the class is initialized" not when it is loaded - and you are not instanciating or accessing any member of it. – user85421 Oct 03 '18 at 07:17
  • @CarlosHeuberger Mind elaborating in an answer? – Gonen I Oct 03 '18 at 07:20
  • [Java Language Specification](https://docs.oracle.com/javase/specs/jls/se11/html/jls-12.html#jls-12.4) – user85421 Oct 03 '18 at 07:23
  • loadClass does not call the static block read more - https://stackoverflow.com/questions/8100376/class-forname-vs-classloader-loadclass-which-to-use-for-dynamic-loading – Subir Kumar Sao Oct 03 '18 at 07:24

1 Answers1

0

The static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class).

Reference : https://www.geeksforgeeks.org/g-fact-79/

In your case, you are just loading the class and not initializing the object of the class.

Jignesh M. Khatri
  • 1,407
  • 1
  • 14
  • 22