JVM 什么时候加载类? [英] When does the JVM load classes?

查看:26
本文介绍了JVM 什么时候加载类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下课程:

class Caller {
  public void createSomething() {
    new Something();
  }
}

将执行此行:

static void main() {
   Class<?> clazz = Caller.class;
}

导致 JVM 加载类 Something 还是类加载延迟到方法 createSomething() 被调用?

cause the JVM to load the class Something or is the class loading deferred until the method createSomething() is called?

推荐答案

仅当您需要有关该类的信息时才加载该类.

A class is loaded only when you require information about that class.

public class SomethingCaller {
    public static Something something = null; // (1) does not cause class loading
    public static Class<?> somethingClass = Something.class; // (2) causes class loading

    public void doSomething() {
        new Something(); // (3) causes class loading
    }
}

第 (2) 行 &(3) 会导致类被加载.Something.class 对象包含只能来自类定义的信息(第 (2) 行),因此您需要加载该类.对构造函数 (3) 的调用显然需要类定义.类上的任何其他方法也是如此.

The lines (2) & (3) would cause the class to be loaded. The Something.class object contains information (line (2)) which could only come from the class definition, so you need to load the class. The call to the constructor (3) obviously requires the class definition. Similarly for any other method on the class.

但是,第 (1) 行不会导致加载类,因为您实际上不需要任何信息,它只是对对象的引用.

However, line (1) doesn't cause the class to be loaded, because you don't actually need any information, it's just a reference to an object.

在您更改的问题中,您询问是否引用 Something.class 会加载该类.是的,它确实.它在执行 main() 之前不会加载类.使用以下代码:

In your changed question, you ask whether referring to Something.class loads the class. Yes it does. It does not load the class until main() is executed though. Using the following code:

public class SomethingTest {
    public static void main(String[] args) {
        new SomethingCaller();
    }
}

public class SomethingCaller {
    public void doSomething() {
        Class<?> somethingClass = Something.class;
    }
}

public class Something {}

此代码不会导致加载 Something.class.但是,如果我调用 doSomething(),则会加载该类.要对此进行测试,请创建上述类,编译它们并删除 Something.class 文件.上面的代码不会因 ClassNotFoundException 而崩溃.

This code does not cause the Something.class to be loaded. However, if I call doSomething(), the class is loaded. To test this, create the above classes, compile them and delete the Something.class file. The above code does not crash with a ClassNotFoundException.

这篇关于JVM 什么时候加载类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆