Why static block is not executed

孤街醉人 提交于 2019-12-10 15:58:09

问题


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



来源:https://stackoverflow.com/questions/49316560/why-static-block-is-not-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!