class 何时被 JVM 加载?

when is class loaded by JVM?

假设我启动网络服务器(或任何其他 java 进程),所有 class(元数据如 class 定义)是否会在 server/process 启动时加载甚至之前 它们在系统中的任何地方使用,或者它们在运行时加载,即仅在创建对象或遇到导入语句时加载?

这个问题是针对 jdk 8 和 jdk 6

首先,在字节码中,没有import语句。字节码只是在各处使用完全限定的名称。

然后,大多数 JVM 的默认行为是 "lazy" 加载 classes。意思是:当你加载 class A 时,JVM 将只加载那些 classA 的所有静态初始化器所需的 classes。

所以,如果A "uses" B和C;然后 B,C 仅在 JVM 执行需要 B 的代码时才加载。 C 待加载。

在编写自己的 class 加载程序时,您当然可以做不同的事情。

Class loading architecture

以下是与您的问题相关的行

ClassLoaders are architected so that at start-up the JVM doesn't need to know anything about the classes that will be loaded at runtime.

Initially when a JVM starts up, nothing is loaded into it. The class file of the program being executed is loaded first and then other classes and interfaces are loaded as they get referenced in the bytecode being executed.

JVM does lazy loading of the classes. Means classes are loaded as they are required directly OR INDIRECTLY.