为什么不执行静态块

Why static block is not executed

根据 java 文档,初始化 class 时执行静态块。

谁能告诉我为什么当我 运行 下面的代码时没有执行静态块?

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();
    }
}

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 [...]

您目前没有进行上述任何操作。 因此,通过替换

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

以此为例

A object = new A();

会给你结果。

引用 A.class 不会导致执行 A 的静态初始化程序,请参阅 here

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

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