静态方法总是加载到内存中吗? [英] Are static methods always loaded into memory?
问题描述
假设我有一个带有一些Utils类的Java项目,并且那些类只有 static
方法和成员。
Say that I have a Java project with some "Utils" classes, and that those classes have only static
methods and members.
运行我的应用程序后,这些方法和成员是否会自动加载到内存中?或者只有在我按照代码调用类时才会发生这种情况?
Once I run my application, are those methods and members automatically loaded into memory? Or that only happens once I call the class along the code?
编辑:一些示例代码来说明我的问题。
Some sample code to illustrate my question.
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?
}
}
如果该类有其他静态成员和方法怎么办? ,如果它只在我调用其中一个时加载,其他方法也被加载?
And what if that class have other static members and methods, and if it loads only once I call one of them, the other methods are loaded as well?
推荐答案
静态方法(和非静态方法和静态/成员变量)不直接加载到内存中:声明类完整地加载到内存中,包括所有声明的方法和字段。因此,加载静态/非静态方法/字段的方式没有区别。
Static methods (and non-static methods, and static/member variables) are not loaded into memory directly: the declaring class is loaded into memory in its entirety, including all declared methods and fields. As such, there is no difference in the way that static/non-static methods/fields are loaded.
类只在第一次被类加载器加载时由其他代码引用。这构成了按需初始化习惯用语的基础。
A class is only loaded by a class loader the first time it is referenced by other code. This forms the basis of the Initialization on demand idiom.
这篇关于静态方法总是加载到内存中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!