静态方法总是加载到内存中吗?

假设我有一个带有一些“Utils”类的Java项目,并且那些类只有static方法和成员。

一旦我运行我的应用程序,这些方法和成员是否自动加载到内存中? 或者只有在我沿着代码调用类时才会发生?

编辑:一些示例代码来说明我的问题。

RandomUtils.java

 public class RandomUtils { private static Random rand = new Random(); public static int randInt(int min, int max) { // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive return rand.nextInt((max - min) + 1) + min; } } 

MainClass.java

 public class MainClass { public static void main(String[] args) { // Some other operations. Is my class already loaded here? int randomNumber = RandomUtils.randInt(1,10); // Or is it only loaded here? } } 

如果该类有其他静态成员和方法,如果它只在我调用其中一个时加载,那么其他方法也被加载了怎么办?

静态方法(以及非静态方法和静态/成员变量)不会直接加载到内存中:声明类完整地加载到内存中,包括所有声明的方法和字段。 因此,加载静态/非静态方法/字段的方式没有区别。

类仅在第一次被其他代码引用时由类加载器加载。 这构成了按需初始化习语的基础。

当(在其他条件下)第一次调用static方法时,将加载您的类。 见参考文献 。

调用class时,静态方法只加载一次。 在此处输入图像描述

college =“ITS”是一个静态变量

一旦你打电话给它,它就会发生。