How jvm checks a class is loaded or not when a class is used first time

shao :

Question

when jvm runs following code

MyObject o=new MyObject() //first access MyObject

we know jvm will starting load class of MyObject, but i wonder how jvm know MyObject is not loaded.

Motivation

i wonder to know because if jvm runs these codes

public class Main{
  public static void main(){
     ClassLoader myLoader = new ClassLoader(null) {
            @Override
            protected Class<?> findClass(String name) throws ClassNotFoundException {
                // omitted here
            }
        }
     myLoader.loadClass("MyObject"); //#1
     MyObject o=new MyObject() //#2
  }
}

we knows that without #1, MyObject will be loaded by classloader of class Main,but with #1,will class of MyObject loaded at #2, and how jvm makes judges?

meriton :

Each ClassLoader keeps a list of the classes it has loaded so far.

If two different ClassLoader load a class of the same name, these are treated by the runtime as two separate unrelated classes. That is useful because it allows different versions of the same class to coexist at runtime. For instance, we can deploy several web applications developed by different teams into the same JVM, each with its own libraries, freeing the developers of the various applications from coordinating the versions of the libraries they use.

In your case, if we do new MyObject() in class Main, the class loader that loaded class Main is asked to load class MyObject. That's the system ClassLoader, which knowns nothing of your myLoader. Therefore, the system class loader will load class MyObject again.

You can verify this by adding a static initializer to MyObject:

class MyObject {
    static {
        System.out.println("class MyObject has been loaded");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=345016&siteId=1