静态方法总是加载到内存中吗?
Are static methods always loaded into memory?
假设我有一个 Java 项目,其中包含一些 "Utils" class 类,而那些 class 类只有 static
方法和成员。
一旦我 运行 我的应用程序,那些方法和成员是否会自动加载到内存中?或者只有在我沿代码调用 class 时才会发生这种情况?
编辑:一些示例代码来说明我的问题。
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?
}
}
如果那个 class 有其他静态成员和方法,如果它只加载一次我调用其中之一,其他方法也会加载?
当您调用 class.
时,静态方法只加载一次
college="ITS"是静态变量
它会在您调用 class 时发生。
静态方法(以及non-static方法和static/member变量)不直接加载到内存中:声明的class被完整加载到内存中,包括所有声明的方法和字段。因此,加载 static/non-static methods/fields 的方式没有区别。
A class 仅在第一次被其他代码引用时由 class 加载程序加载。这构成了 Initialization on demand idiom.
的基础
您的 class 在(除其他条件外)首次调用其 static
方法时加载。参见 reference。
假设我有一个 Java 项目,其中包含一些 "Utils" class 类,而那些 class 类只有 static
方法和成员。
一旦我 运行 我的应用程序,那些方法和成员是否会自动加载到内存中?或者只有在我沿代码调用 class 时才会发生这种情况?
编辑:一些示例代码来说明我的问题。
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?
}
}
如果那个 class 有其他静态成员和方法,如果它只加载一次我调用其中之一,其他方法也会加载?
当您调用 class.
college="ITS"是静态变量
它会在您调用 class 时发生。
静态方法(以及non-static方法和static/member变量)不直接加载到内存中:声明的class被完整加载到内存中,包括所有声明的方法和字段。因此,加载 static/non-static methods/fields 的方式没有区别。
A class 仅在第一次被其他代码引用时由 class 加载程序加载。这构成了 Initialization on demand idiom.
的基础您的 class 在(除其他条件外)首次调用其 static
方法时加载。参见 reference。