Introduction to Java class loaders
The class loader is used to load the. Class file to the virtual machine and generate a java. lang. class Object.
Class Loader Structure
The built-in class loaders of jvm include:
Bootstrap loader
The boot loader, also known as the root loader, is a nvwa-level loader, rt. classes in jar are loaded by them, such as java. lang. object, java. lang. string, java. lang. class, java. lang. classLoader and so on. I can't even play with Java without it, but it is not written in Java itself (if it is written in Java, it's strange. Who will load it ?). Because it is not a Java Object, Object. class. getClassLoader () returns null.
Extension Loader
The extension loader loads the jre extension package. The directory is jre/lib/ext.
System loader
The system loader, also known as the Application Loader (because it specifically loads classes in the application), is responsible for loading the directory specified by the Environment Variable CLASSPASS. In fact, the environment variable CLASSPASS is generally ". ", that is, the current directory, so the classes in the application are loaded by the system loader by default.
Custom Class Loader
For example:
public class TestClassLoader extends ClassLoader{ @Override protected Class
findClass(String name) throws ClassNotFoundException { try { String filePath=System.getProperty("user.dir")+File.separator+"src"+File.separator+name.replace(".", File.separator)+".class"; byte[] bytes = Files.readAllBytes(new File(filePath).toPath()); return defineClass(name, bytes, 0, bytes.length); } catch (IOException e) { throw new ClassNotFoundException(name,e); } } public static void main(String[] args) throws Exception { TestClassLoader classLoader = new TestClassLoader(); Class
class1 = classLoader.loadClass("test.Test"); Test test = (Test)class1.newInstance(); }}
Inheritance relationship
Custom loader> inherit> system loader> inherit> extended loader> inherit> boot loader.
You can use ClassLoader. getParent () to obtain the parent loader of the loader. If the parent loader of A Class Loader is a bootstrap loader, then ClassLoader. getParent () will return null.
The inheritance relationship of the loader is not the inheritance relationship of the Java class. The custom loader and the system loader and the extended loader both inherit from the ClassLoader, so there is no parent-child relationship on the class inheritance organization, from the perspective of class inheritance, they are brothers.
Class loaders have three mechanisms: Delegate
If the parent loader can be loaded, the parent loader can be loaded.
Visibility
1. The class loaded by the subclass loader can access the class loaded by the parent class loader.
2. The class loaded by the parent class loader cannot access the class loaded by the subclass loader.
3. The classes loaded by two loaders without inheritance relationships cannot be accessed from each other.
Singularity
Load only once, not repeatedly.