When does the JVM load classes?

前端 未结 3 1001
旧巷少年郎
旧巷少年郎 2020-12-08 08:51

Assume I have the following class:

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

Would executing this line:

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 09:05

    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
        }
    }
    

    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.

    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.

    EDIT: 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 {}
    

    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.

提交回复
热议问题