The Java class loader is a tool responsible for loading. class files to the memory. It is said that only after. Class is loaded as memory can it be called bytecode.
The Java class loader has a parent-child cascade relationship:
Bootstrap --> extclassloader --> appclassloader --> Custom Class Loader
-- Bootstrap and loader, responsible for loading RT. jar is a class provided by Java. It is written by C ++. Therefore, when we want to get it in a program, null is returned.
-- Extclassloader: extends the class loader to load classes under the JRE/lib/EXT directory.
-- The appclassloader application class loader is used to load classes under classpath.
-- The Custom Class Loader inherits from the classloader and can implement custom class loading methods.
Java class loading uses the so-called "full delegation" mechanism:
-- When a class is to be loaded, it starts from the class loader responsible for loading the class, and goes back to all parent class loaders. If a class loader is successfully loaded during the process, the load is complete. If all parent class loaders In the rollback cannot be loaded (PS: loading failure means that the class loader cannot find the class with the same name as the class to be loaded.), Then it is returned to the Class Loader responsible for loading this type for loading. If it still cannot be loaded, it will throw classnotfoundexception. That is to say, if Grandpa Dad can load this class, load the class. If he cannot load the class, load the class to his son/grandson. This is similar to the instantiation class. when instantiating a class, JVM also instantiates all direct and indirect parent classes of this class.
-- Advantages of the entire delegation mechanism: ensures the security of class loading. For example, if we write a string class by ourselves, when the class starts to load, it will go back to the bootstrap root loader and find that it can load the string class, however, he will not load the string class we wrote, but will load the string class within his own scope, which ensures the correct loading of the string class, instead of overwriting the original string class with the custom string class.
Custom class loaders appear in many places. For example, many custom class loaders exist in Tomcat. To implement a custom class loader, you only need to inherit the classloader and then override the findclass method:
1 public class MyClassLoader extends ClassLoader {2 3 @Override4 protected Class<?> findClass(String name) throws ClassNotFoundException {5 return super.findClass(name);6 }7 8 }