【问题标题】:Are static methods always loaded into memory?静态方法是否总是加载到内存中?
【发布时间】:2016-01-11 13:39:18
【问题描述】:

假设我有一个带有一些“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?
        }
}

如果该类有其他静态成员和方法,并且如果它仅在我调用其中一个时加载,那么其他方法也会被加载?

【问题讨论】:

标签: java static static-methods


【解决方案1】:

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

类仅在第一次被其他代码引用时才由类加载器加载。这构成了Initialization on demand idiom 的基础。

【讨论】:

  • 所以唯一真正的区别是我不需要为此创建对象,对吧?
  • 你不需要创建那个类的instance,不。
  • 我的意思是,staticnon-static 都会在调用和实例化后将类完全加载到内存中,对吧?
  • 你不能加载类的一部分。您必须加载整个类才能使用其中的任何一个。
【解决方案2】:

当(除其他条件外)第一次调用其static 方法时,将加载您的类。见reference

【讨论】:

    【解决方案3】:

    静态方法只在你调用类时加载一次。

    college="ITS" 是一个静态变量

    【讨论】:

    • college 是一个静态变量,调用类时只加载一次
    • 它是如何显示的? college 实际用于什么?图表中是否有一些代码?
    • s1 和 s2 是类对象。使用这些对象我们可以直接访问大学变量的值。静态方法也是如此。
    【解决方案4】:

    它会在你调用类时发生。

    【讨论】:

      猜你喜欢
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 2014-02-10
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多