In what order do static/instance initializer blocks in Java run?

前端 未结 8 1646
心在旅途
心在旅途 2020-11-22 17:01

Say a project contains several classes, each of which has a static initializer block. In what order do those blocks run? I know that within a class, such blocks are run in

8条回答
  •  借酒劲吻你
    2020-11-22 17:48

    See section 12.4 and 12.5 of the JLS version 8, they go into gory detail about all of this (12.4 for static and 12.5 for instance variables).

    For static initialization (section 12.4):

    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.

    (and several weasel-word clauses)

提交回复
热议问题