Class loading vs class initialization

 ̄綄美尐妖づ 提交于 2019-12-01 05:46:17

问题


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.

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

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.

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?


回答1:


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

5.5. Initialization

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

Going backwards to the Linking section

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

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



来源:https://stackoverflow.com/questions/19100002/class-loading-vs-class-initialization

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