Narendra Pathai
Narendra Pathai

Reputation: 41935

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.

Upvotes: 2

Views: 2297

Answers (1)

Joachim Sauer
Joachim Sauer

Reputation: 308001

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).

Upvotes: 2

Related Questions