编程语言
首页 > 编程语言> > java – 类加载与类初始化

java – 类加载与类初始化

作者:互联网

我一直认为类加载和类初始化是同义的,并且通常在some way or the other for the first time使用初始化/加载的类时按需发生.但是现在我从this answer on SO regarding the behavior of final static fileds that holds compile time constants知道我的信念是错误的.

请注意以下内容,很明显类加载和初始化是两种不同的机制.

As a side point, please note the distinction between class loading and
class initialization: only the latter’s occurrence is precisely
specified by the JLS. Class loading can happen at any time.

但有人可以解释Java语言中类加载和类初始化之间的区别.通常直觉说初始化应始终先加载,但我完全错了.可以在没有加载类的情况下进行初始化吗?

解决方法:

Java Virtual Machine Specification, Chapter 5. Loading, Linking, and Initializing ,你可以找到这个信息(强调我的):

5.5. Initialization

Prior to initialization, a class or interface must be linked, that is, verified, prepared, and optionally resolved.

回到链接部分

5.4. Linking

Linking a class or interface involves verifying and preparing that class or interface, its direct superclass, its direct superinterfaces, and its element type (if it is an array type), if necessary. Resolution of symbolic references in the class or interface is an optional part of linking. This specification allows an implementation flexibility as to when linking activities (and, because of recursion, loading) take place, provided that all of the following properties are maintained:

  • A class or interface is completely loaded before it is linked

因此,我们可以推断在初始化之前必须加载类或接口.

标签:jls,java,jvm
来源: https://codeday.me/bug/20190725/1532950.html