Class loader

The loading of classes is implemented externally to the JVM. For any class, its uniqueness within the Java virtual machine must be established by both the classloader that loads it and the class itself. The JVM provides an intermediate class loader.

Bootstrap ClassLoader

Classes that are responsible for loading classes in the JAVA_HOME\lib directory or in the path specified by the -xBootCLASspath parameter and recognized by the virtual machine (by filename, such as rt.jar).

The jar ‘package in the lib directory of the JRE is loaded

Extension ClassLoader

Is responsible for loading class libraries in the JAVA_HOME\lib\ext directory, or in the path specified by the java.ext.dirs system variable.

The jar in the jre/lib/ext directory is loaded

Application ClassLoader

Responsible for loading class libraries on the user’s classpath. The JVM loads classes through the parent delegate model, but we can also implement custom class loaders by inheriting java.lang.ClassLoader.

img
public class Test {



    public static void main(String[] args){

        Test test = new Test();

        Class<? extends Test> testClass = test.getClass();

        System.out.println("testClass = " + testClass);

        // AppClassLoader

        System.out.println("testClass.getClassLoader() = " + testClass.getClassLoader());

        // ExtClassLoader

        System.out.println("testClass.getClassLoader().getParent() = " + testClass.getClassLoader().getParent());

// null: actually starts the class (root) loader. The bottom layer is implemented by C/C ++. Java does not get this object

        System.out.println("testClass.getClassLoader().getParent().getParent() = " + testClass.getClassLoader().getParent().getParent());

    }

}

Copy the code

Parent delegation mechanism

When a class receives a classload request, it first does not attempt to load the class itself. Instead, it delegates the request to the parent class. This is true of every hierarchical classloader, so all load requests should be passed to the starting classload. The subclass loader will try to load the request itself only if the parent Class loader reports that it is unable to complete the request (the desired Class is not found in its load path).

One advantage of parental delegation is that, for example, loading the java.lang.Object class in the rt.jar package, whichever loader loads the class, ultimately delegates the load to the top-level launcher class loader. This ensures that different classloaders will end up with the same Object.

img