3 basic types of loader

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u013219624/article/details/89255860

0. loaded custom class

public class ClassLoaderTest {
    public void say() {
        System.out.println("This is Test.");
    }
}

1. The system default class loader
BootStrap loader: rt.jar main load, which is the basis of Java class libraries, there are other types of String
Extension loader: the main load jre / lib / ext JAR directory, which contains some of the encrypted Java a method of
Application (System) loader: loading the classpath jar

2. The class loader three mechanisms
delegate: When loading a Class, the current loader will first delegation parent loader loads if the parent fails to load the loader to load it
visible: Father loader loads the Class, sub-loaders are It is visible, and the child class loader to load the class parent does not know
a single: a class can only be loaded once

3. Some examples

  1. Start class loader is to obtain less than

    ClassLoader classLoader = String.class.getClassLoader(); (classLoader永远都是null)
    
  2. Extension classpath can not be loaded under category (there will be ClassNotFoundException)

    ClassLoader classLoader = AccessBridge.class.getClassLoader();
    Class<?> loadClass = classLoader.loadClass("test.ClassLoaderTest");
    
  3. Application classpath under load class, no problem

    ClassLoader classLoader = TempDemo.class.getClassLoader();
    Class<?> loadClass = classLoader.loadClass("test.ClassLoaderTest");
    Object obj = loadClass.newInstance();
    Method method = loadClass.getMethod("say");
    method.invoke(obj);
    

4. Display class loader API calls

Class<?> loadClass = Class.forName("test.ClassLoaderTest");
Object obj = loadClass.newInstance();
Method method = loadClass.getMethod("say");
method.invoke(obj);

Guess you like

Origin blog.csdn.net/u013219624/article/details/89255860