classloader
Class loader (ClassLoader) is used to load class bytecode to Java virtual machine. In general, Java virtual machines use Java classes in the following way: Java source files are converted to Java after passing through JavacBytecode file (.Class file). The class loader is responsible for reading the Java byte code and converting it into an instance of the java.lang.Class class. Each of these instances is used to represent a Java class. The actual situation may be more complicated, for example.Java byte code may be generated dynamically by tools or downloaded through the network.
Class and class loader
Although class loaders are only used to implement class loading actions, their role in Java programs is far beyond the class loading phase. For any class, its uniqueness in Java virtualization needs to be determined by the class loader that loads it along with the class itself. To speak more popular, compare two categories.Whether two classes are “equal” makes sense only if they are loaded by the same class loader. Otherwise, even if the two classes originate from the same class file, the two classes must not be equal as long as their class loaders are different. The “equivalence” referred to here includes the Class pair of the representative class.The equal method of the image, isAssignableFrom (), isInstance () method and the result returned by instance keyword.
Class loader classification:
It is mainly divided into Bootstrap Class Loader, Extension Class Loader, Application Class Loader and User Defined Class Loader.
Start the class loader (Bootstrap ClassLoader):
This class loader is implemented in C++ language, not a subclass of ClassLoader. Mainly responsible for loading all the class files stored in JAVA_HOME/jre/lib/rt.jar, or by – XbootclasA file named rt.jar in the path specified by the sPath parameter.
The extended class loader (Extension ClassLoader):
This loader, implemented by sun. misc. Launcher $ExtClassLoader, is responsible for loading in the AVA_HOME / lib / ext directory or in the path specified by the java. ext. dirs system variableAll class libraries.
Application class loader (Application ClassLoader):
This loader is implemented by sun. misc. Launcher $AppClassLoader, which loads the jars and directories corresponding to the classpath. In general, this is the default class loader in the program.
The custom class loader (User Defined ClassLoader):
Developers inherit classloaders implemented by ClassLoader abstract classes themselves, based on self-developed classLoaders that can be used not to load Classpaths (such as jars or binary bytecodes downloaded from the network), but also to load class filesBefore doing some small moves, such as encryption.
Parent delegation model:
The hierarchical relationship between the class loaders shown in the figure above is called the parent delegation model of the class loader. The parent delegation model requires that all classloaders except the top-level startup classloader should have their own parent classloader. The parent child relationship between class loaders is generally not inherited.To implement, we use composite relationships to reuse the code of the parent loader.
-
public abstract class ClassLoader {
-
-
private static native void registerNatives();
-
static {
-
registerNatives();
-
}
-
-
// The parent class loader for delegation
-
private ClassLoader parent;
-
-
// Hashtable that maps packages to certs
-
private Hashtable package2certs = new Hashtable(11);
-
}
The process of parent delegation: If a class loader receives a class load request, it will not load the class itself first, but delegates the request to the parent class loader to complete, as is the case with each level of class loader, so all load requests should eventually be sent to the top-level startup classIn a loader, the child tries to load itself only when the parent loader feeds back that it cannot complete the load request (there is no such class in the scope it manages).
One obvious advantage of using the parent delegation model to organize the relationships between class loaders is that Java classes, along with their class loaders, have a hierarchy of priorities, such as java. lang. Object stored in RT. jar, regardless of which class addsThe loader ultimately delegates the load to the startup classloader, so the Object class is the same class in all classloader environments of the program. On the contrary, if there is no parent delegation model, it is done by each class loader, if the user writes a class named java.lClasses of ang. Object, placed in the classpath, may appear in many different Object classes in the application, and the most basic security behavior in the Java type system is not guaranteed.
Class loader SPI:
java.lang.ClassLoader Several key methods provided by the class:
loadClass: This method is responsible for loading a class with the specified name, first looking for it from the loaded class if it is not found, from parent ClassLoader [ExtClassLoader], and from Bootstrap ClassL if it is not loaded.Try loading in loader (findBootstrapClassOrNull method), if the load fails, throw an exception ClassNotFoundException and load it by calling your own findClass method.You can override this method if you want to change the loading order of the classes; if the loading order is the same, you can override the findClass method for special processing, such as decryption, fixed path finding, and so on. When the Class object is still not acquired through the entire search class process, ClassN is thrown.OtFoundException exception.
If class needs resolve, link is called by calling resolveClass.
-
protected synchronized Class<?> loadClass(String name, boolean resolve)
-
throws ClassNotFoundException
-
{
-
// First, check if the class has already been loaded
-
Class c = findLoadedClass(name);
-
if (c == null) {
-
try {
-
if (parent != null) {
-
c = parent.loadClass(name, false);
-
} else {
-
c = findBootstrapClassOrNull(name);
-
}
-
} catch (ClassNotFoundException e) {
-
// ClassNotFoundException thrown if class not found
-
// from the non-null parent class loader
-
}
-
if (c == null) {
-
// If still not found, then invoke findClass in order
-
// to find the class.
-
c = findClass(name);
-
}
-
}
-
if (resolve) {
-
resolveClass(c);
-
}
-
return c;
-
}
findLoadedClass This method is responsible for finding loaded classes from the cache of the current ClassLoader instance object, calling the native method.
-
protected final Class<?> findLoadedClass(String name) {
-
if (!checkName(name))
-
return null;
-
return findLoadedClass0(name);
-
}
-
-
private native final Class findLoadedClass0(String name);
findClass This method throws a ClassNotFoundException exception directly, so it loads the classes in a custom way by overwriting the loadClass or this method.
-
protected Class<?> findClass(String name) throws ClassNotFoundException {
-
throw new ClassNotFoundException(name);
-
}
findSystemClass This method looks for the class from sun. misc. Launcher $AppClassLoader, and if it is not found, continues to look for it from BootstrapClassLoader, and if it is still not found, returns null
-
protected final Class<?> findSystemClass(String name)
-
throws ClassNotFoundException
-
{
-
ClassLoader system = getSystemClassLoader();
-
if (system == null) {
-
if (!checkName(name))
-
throw new ClassNotFoundException(name);
-
Class cls = findBootstrapClass(name);
-
if (cls == null) {
-
throw new ClassNotFoundException(name);
-
}
-
return cls;
-
}
-
return system.loadClass(name);
-
}
defineClass This method is responsible for converting binary byte streams into Class objects, which is important for custom class loaders. If the format of the binary bytecode does not conform to the JVM class file format specification, a ClassFormatError exception is thrown; if generatedA NoClassDefFoundError is thrown if the class loaded is protected, has a different signature, or the class name begins with java. The SecurityException exception is thrown.
-
protected final Class<?> defineClass(String name, byte[] b, int off, int len,
-
ProtectionDomain protectionDomain)
-
throws ClassFormatError
-
{
-
return defineClassCond(name, b, off, len, protectionDomain, true);
-
}
-
-
// Private method w/ an extra argument for skipping class verification
-
private final Class<?> defineClassCond(String name,
-
byte[] b, int off, int len,
-
ProtectionDomain protectionDomain,
-
boolean verify)
-
throws ClassFormatError
-
{
-
protectionDomain = preDefineClass(name, protectionDomain);
-
-
Class c = null;
-
String source = defineClassSourceLocation(protectionDomain);
-
-
try {
-
c = defineClass1(name, b, off, len, protectionDomain, source,
-
verify);
-
} catch (ClassFormatError cfe) {
-
c = defineTransformedClass(name, b, off, len, protectionDomain, cfe,
-
source, verify);
-
}
-
-
postDefineClass(c, protectionDomain);
-
return c;
-
}
resolveClass This method is responsible for completing links to Class objects, and if linked, returns directly.
Common abnormality:
ClassNotFoundException This is the most common exception. The reason for this exception is that the class file was not found when the class was loaded in the current ClassLoader.
NoClassDefFoundError This exception is because the other class referenced in the loaded class does not exist, such as to load A, and A embezzles B, B does not exist, or the current ClassLoader cannot load B, which throws the exception.
LinkageError This exception is more likely to occur when you customize a ClassLoader, mainly because the class has already been loaded in the ClassLoader, and repeated loading will cause the exception.