简体   繁体   中英

How does Java find already loaded classes?

I know that Java uses the ClassLoader hierarchy for loading the classes.

For example a program:

public void test(){
    A a = new A(); // Line 1 The class is accessed first time here so it should be loaded and defined

    A ab = new A(); //Line 2 How can the second line be represented?
}

The first line of the code is similar to

Thread.currentThread().getContextClassLoader().loadClass("A");

So the class is loaded and defined to create instance of Class .

Now the question is when the second line is executed the Class A is referred again, will Java not lookup for the class again and return the same loaded instance of the Class?

As the Java classloader document says that every class loader should maintain the instances of loaded classes and return the same instances for the next call.

Where does Java keep the loaded classes? ClassLoader class has a Vector of classes which is called by VM to add the loaded classes.

Maybe the question is a bit confusing, basically I am trying to figure out from which method are the already loaded classes returned. I tried to keep a debug point in the loadClass() method but it is not called for the Line 2 .

The loadClass() method of ClassLoader has findLoadedClass method but that too is not called.

If you want to "translate" the mention of A to any method call, then the closest you could get is not loadClass() but Class.forName() .

This method call queries the classloader for the class, which may or may not trigger class loading (and the caller doesn't even care). It will simply return a fully loaded (and initialized, if you don't use the three-argument version ) class back to the caller.

And once the class has been loaded, the class loader no longer get's invoked when the class is used (as the name suggests, it's job is done, once it loaded the class).

package java_language;

public class NewClass {

    Java_language j;

    public NewClass() throws ClassNotFoundException {
        j=new Java_language();
         if (Class.forName("java_language.Java_language", true, Thread.currentThread().getContextClassLoader()).equals(j.getClass())) {
            System.out.println("CLass has been loaded");
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
       new NewClass();

    }

}

package java_language;

public class Java_language {

    static Java_language java_language = null;
    public Java_language() {
        System.out.println("Stack Overflow");
    }
}

Ans is:
回答截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM