Search code examples
javaclassloader

When a java class gets loaded, does it load the class only referenced (but not instantiated) in this class as well?


When a java class gets loaded, does it load the class only referenced (but not instantiated) in this class as well? I find its not loading until the referenced class gets instantiated or any static field is assigned a value. However, I learnt that this behavior varies JVM to JVM. Is it true?


Solution

  • There are these two overloaded methods to load class.

    loadClass(name, resolve);
    loadClass(name);
    

    Here resolve is a boolean flag and when it is true, it will resolve all the referenced classes also. When it is false it doe's not load referenced classes.

    Note that for any class you will load, the resolve variable will always be true. It is only when the system is recursively calling loadClass() that it may set this variable false because it knows the class it is asking for is already resolved.

    Here, loadClass(name); calls loadClass(name, false);