本文介绍了类加载与类初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为类加载和类初始化是同义的,并且通常在。但是现在我从知道我认为是错的。

I always thought that class loading and class initialization are synonymous and usually happens on demand when the class being initialized/loaded is used in some way or the other for the first time. But now I know from this answer on SO regarding the behavior of final static fileds that holds compile time constants that my belief is wrong.

请注意以下内容,非常清楚 loading 初始化是两种不同的机制。

Please note the following which makes it quite clear that class loading and initialization are two different mechanism.

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

But can someone please explain the difference between class loading and class initialization in Java language. Normally intuition says that initialization should always be preceded by loading but I am be completely wrong. Can initialization ever happen without a class getting loaded?

推荐答案

来自,你可以找到这个信息(强调我的):

From Java Virtual Machine Specification, Chapter 5. Loading, Linking, and Initializing , you can find this info (emphasys mine):

在初始化之前,必须链接一个类或接口 ,即验证,准备和可选地解析。

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

返回链接部分

链接类或接口涉及验证和准备该类或接口,其直接超类,其直接超接口及其元素类型(如果它是数组类型) ,如有必要。类或接口中符号引用的解析是链接的可选部分。此规范允许实现灵活性,以便何时发生链接活动(以及由于递归,加载),前提是维护所有以下属性

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

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

So, we can infer that a class or interface must be loaded before being initialized.

这篇关于类加载与类初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 07:58