JVM何时加载类? [英] When does the JVM load classes?

查看:78
本文介绍了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天全站免登陆