0

I have this piece of code, i am running it using -verbose:class option to see the classes that got loaded. To my surprise, it shows it loaded class A1 and A2 but the static block is not getting called.

Can someone plz explain this behavior

package P1;



import java.lang.reflect.InvocationTargetException;

public class DemoReflection {

    static {
        System.out.println("Loading Demo");
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException,
            InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        System.out.println("A2 " + A2.class.getClassLoader().getClass());
        System.out.println("Demo " + DemoReflection.class.getClassLoader().getClass());
        System.out.println("A1 " + A1.class.getClassLoader().getClass());
    }

}

class A1 {
    static {
        System.out.println("Loading A1");
    }
}

class A2 extends A1 {

    static {
        System.out.println("Loading A2");
    }

    public A2() {
        System.out.println("m2");
    }

    public void m1() {
        System.out.println("m1");
    }
}

class A3 {

    static int a3Id = 3;

    static {
        System.out.println("Loading A3");
    }

}

Output: enter image description here

Payal Bansal
  • 725
  • 5
  • 17
  • Possible duplicate of [When is the static block of a class executed?](https://stackoverflow.com/questions/9130461/when-is-the-static-block-of-a-class-executed) – Ori Marko Jul 16 '19 at 14:22

2 Answers2

3

The JLS §8.7 says that :

A static initializer declared in a class is executed when the class is initialized (§12.4.2).

So what does the initialization mean? Let's refer to JLS §12.4.2. This describes detailed initialization procedure. However point JLS §12.4.1 might be more appropriate here. It says that :

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
  • Noone of those options apply to your case so static block is not called.

    Michał Krzywański
    • 15,659
    • 4
    • 36
    • 63
    0

    Simple version: Static block runs only at first time you make an object or you access a static member of that class.

    zlaval
    • 1,941
    • 1
    • 10
    • 11