[Java] class loading mechanism and java class loading mechanism

Source: Internet
Author: User

[Java] class loading mechanism and java class loading mechanism
Parental Delegation Model:

Three types of Loading Methods: BootStrap Loader, Extension Loader, and Application Loader. The three tubes have different scopes. None of them call the parent class and use the loader of the parent class to load the class.

However, the getParent method of Extension Loader returns null because BootStrap Loader is written in C ++ and does not specify the return value. Therefore, NULL is returned.


BootStrap Loader is part of the virtual machine itself.

Extension Loader, which is implemented in Java. All are inherited from the abstract class java. lang. ClassLoader. Independent from JVM.

Loading range of the three classes

BootStrap Loader: <Java_Runtime_Home>/lib

Extension Loader: <Java_Runtime_Home>/lib/ext or loaded to the memory by the class library specified by the system variable java. ext. dir.

Application Loader is responsible for loading the specified class library in the system CLASSPATH to the memory.


Why is this model used?

The next two class loaders can be called directly.

Java classes along with their class loaders have a level of priority. Without this model, if we accidentally define a class with the same name as the system, then the class of the system will not be executed. Errors cannot be found during compilation, but errors may be reported during runtime, which may cause serious consequences.


<span style="font-size:14px;">protected synchronized Class<?> loadClass(String name, boolean resolve)throws ClassNotFoundException{// First, check if the class has already been loadedClass 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;}</span>

The parent-child delegation model is implemented through the loadClass () method. You can clearly understand the entire process according to the code and comments in the Code: first check whether the model has been loaded, if no, the loadClass () method of the parent loader is called. If the parent loader is empty, the start class loader is used as the parent loader by default. If the parent class loader fails to load, the ClassNotFoundException is thrown first, and then the findClass () method is called for loading.

Damage parent-child Model

If you want to destroy the parent-child delegate model, implement the ClassLoader class and override its loadClass method.

In JAVA, whether a class is unique is determined by the class and its loader. That is to say, to compare whether two classes are equal, it makes sense only when these two classes are loaded by the same Class loader. Otherwise, even if these two classes come from the same Class file, as long as the Class loaders that load it are not the same, the two classes must be not equal (here the equality includes the equals () method representing the Class Object of the Class, isAssignableFrom () result of the method, isInstance () method, and instanceof keyword ).


The parent-child delegation mode solves the unified basic classes of each class loader. the more basic classes are loaded by the upper-layer class loaders, the less basic classes are, when the base class wants to call the lower-level user code, it cannot delegate the subclass loader for class loading. To solve this problem, JDK introduces the ThreadContext thread context. The thread context class loader can be set through the setContextClassLoader method of the thread context.


Custom Class Loader


<Span style = "font-size: 14px;"> public class MyClassLoader extends ClassLoader {// class Loader name private String name; // The path of the loaded class is private String path = "D:/"; private final String fileType = ". class "; public MyClassLoader (String name) {// make the system class loader the parent loader of this class Loader super (); this. name = name;} public MyClassLoader (ClassLoader parent, String name) {// display the parent loader super (parent) for the specified class loader; this. name = name;} public String getP Ath () {return path;} public void setPath (String path) {this. path = path ;}@ Override public String toString () {return this. name;}/*** get. byte array of the class file ---- get the resource * @ param name * @ return */private byte [] loaderClassData (String name) {InputStream is = null; byte [] data = null; byteArrayOutputStream baos = new ByteArrayOutputStream (); this. name = this. name. replace (". ","/"); try {is = new FileI NputStream (new File (path + name + fileType); int c = 0; while (-1! = (C = is. read () {baos. write (c);} data = baos. toByteArray ();} catch (Exception e) {e. printStackTrace ();} finally {try {is. close (); baos. close ();} catch (IOException e) {e. printStackTrace () ;}} return data;}/*** get the Class Object ------ parse data */@ Override public Class <?> FindClass (String name) {byte [] data = loaderClassData (name); return this. defineClass (name, data, 0, data. length);} public static void main (String [] args) throws ClassNotFoundException, InstantiationException, illegalAccessException {// The parent loader of loader1 is the system class loader MyClassLoader loader1 = new MyClassLoader ("loader1"); loader1.setPath ("D:/lib1 /"); // The parent loader of loader2 is loader1 MyClassLoader loader2 = new MyClassLoader (loader1, "loader2"); loader2.setPath ("D:/lib2 /"); // The parent loader of loader3 is the root class loader MyClassLoader loader3 = new MyClassLoader (null, "loader3"); loader3.setPath ("D:/lib3 /"); class clazz = loader2.loadClass ("Sample"); Object object = clazz. newInstance () ;}}</span>


<span style="font-size:14px;">public class Sample {    public Sample(){        System.out.println("Sample is loaded by " + this.getClass().getClassLoader());        new A();    }}public class A {    public A(){        System.out.println("A is loaded by " + this.getClass().getClassLoader());    }}</span>

When loader2.loaderClass ("Sample") is executed, all parent loaders at its upper layer first attempt to load the Sample class. Loader1 successfully loads the Sample class from the D:/lib1/directory. Therefore, laoder1 is the definition class loader of the Sample class. loader1 and loader2 are the initial class loaders of the Sample class.
When loader3.loadClass ("Sample") is executed, all parent loaders at its upper layer first attempt to load the Sample class. The parent loader of loader3 is the root class loader, which cannot load the Sample class, And loader3 successfully loads the Sample class from the D:/lib3/directory, therefore, loader3 is the definition class loader of the Sample class, that is, the initial class loader.
Class A is actively used in the Sample class. When executing the new A () Statement in the constructor of the Sample class, the Java Virtual Machine must first load the Dog class, the Java Virtual Machine will use the definition class loader of the Sample class to load the Dog class. The loading process also uses the parent delegation mechanism.

This part is referenced from: http://www.itzhai.com/java-virtual-machine-notes-custom-class-loader-implementation-and-use-of.html






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.