Why static block is not executed

2019-06-24 06:37发布

问题:

As per java doc, static block is executed when the class is initialized.

Could anyone please tell me why static block is not executed when I run below code?

class A {
    static {
        System.out.println("Static Block");
    }
}

public class Main {

    public static void example1() {
        Class<?> class1 = A.class;
        System.out.println(class1);
    }


    public static void example2() {
        try {
            Class<?> class1 = Class.forName("ClassLoading_Interview_Example.ex1.A");
            System.out.println(class1);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        example1();
    }
}

回答1:

A class's static initialization normally happens immediately before the first time one of the following events occur:

  • an instance of the class is created,
  • a static method of the class is invoked,
  • a static field of the class is assigned,
  • a non-constant static field is used, or [...]

You are currently not doing any of the above. So, by replacing

Class<?> class1 = A.class;
System.out.println(class1);

with this for example

A object = new A();

will give you your result.



回答2:

Referencing A.class will not resulting in executing A's static initializers, see here

Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.

And

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.

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).