Java ClassLoader Mechanism detailed explanation _java

Source: Internet
Author: User
Tags user definition

To get a deeper understanding of ClassLoader, you first need to know what ClassLoader is used for, as the name suggests, it is used to load class files to the JVM for program use. We know thatJava programs can dynamically load class definitions, and this dynamic loading mechanism is implemented through ClassLoader, so imagine the importance of ClassLoader.

See here, perhaps some friends will think of a problem, that is, since ClassLoader is used to load classes into the JVM, then how ClassLoader is loaded? Is it not a Java class?

No, there really is a ClassLoader not written in the Java language, but as part of the JVM implementation, this classloader is the bootstrap ClassLoader (start ClassLoader), This classloader loads Java core APIs while the JVM is running to meet the most basic requirements of Java programs, including user-defined ClassLoader, where the so-called user definition refers to ClassLoader implemented through Java programs, One is Extclassloader, this classloader is used to load the Java extension API, that is,/lib/ext class, one is Appclassloader, This classloader is used to load the class in the Classpath settings directory on the user's machine, and typically the programmer's custom class is loaded by the ClassLoader without specifying ClassLoader.

When running a program, the JVM starts, runs Bootstrap ClassLoader, the ClassLoader loads the Java core APIs (Extclassloader and Appclassloader are also loaded at this time), Then call the Extclassloader load extension API, and finally Appclassloader load the class defined in the Classpath directory, which is the most basic loading process for a program.

The above probably explained the function of ClassLoader as well as a most basic loading process, next will explain the ClassLoader loading way, here will have to talk about ClassLoader here uses the parents delegate pattern to carry on the class loading.

Each custom ClassLoader must inherit ClassLoader this abstract class, and each ClassLoader will have a parent ClassLoader, we can look at ClassLoader this abstract class has a GetParent () method, which is used to return the parent of the current ClassLoader, note that this parent is not a inherited class, but rather a classloader that is specified when the ClassLoader is instantiated. If this parent is null, then the default ClassLoader's parent is bootstrap ClassLoader, what is the use of this parent?

We can consider a situation in which we have customized a clientdefclassloader, We use this custom ClassLoader to load the java.lang.String, so will the String be loaded by this classloader? In fact java.lang.String This class is not loaded by this clientdefclassloader, but by the bootstrap ClassLoader to load, why this? This is actually the reason for the parental delegation pattern, because before any custom ClassLoader loads a class, it delegates its father ClassLoader to load, which is loaded only when the Father ClassLoader fails to load, In the example above, Because Java.lang.String is a class that belongs to the Java Core API, when loading it with Clientdefclassloader, the ClassLoader will first entrust its father ClassLoader to load, as described above, when ClassLoader's When parent is NULL, ClassLoader's parent is bootstrap ClassLoader, so the top level of ClassLoader is Bootstrap ClassLoader, So when the final delegate is to Bootstrap ClassLoader, bootstrap ClassLoader returns the class of String.

Let's take a look at some of the source code in ClassLoader:

 Protected synchronized Class loadclass (String name, Boolean resolve) 
  throws ClassNotFoundException 
    { 
  // First checks whether the class specified by the name has loaded 
  class C = findloadedclass (name); 
  if (c = = null) { 
    try { 
    if (parent!= null) { 
      //If parent is not NULL, invoke parent's loadclass to load 
   = Parent.loadclass (name, false); 
    else { 
      //parent is null, then call Bootstrapclassloader to load 
      c = findBootstrapClass0 (name); 
    } 
    catch ( ClassNotFoundException e) { 
      //If still unable to load successfully, invoke its own findclass to load       
      c = findclass (name); 
    } 
  if (resolve) { 
    resolveclass (c); 
  } 
  return C; 
    

From the above code, we can see that a class loading the approximate process is the same as the example I gave earlier, and we want to implement a custom class, only need to implement the Findclass method.

Why use this parental delegation pattern?

The first reason is that it avoids repeated loading, and when the father has loaded the class, there is no need to classloader it again.

The second reason is that, given security considerations , if we do not use this delegate pattern, we can use a custom string to dynamically override the defined types in the Java Core API, which can have very large security implications, and the way the parents delegate This can be avoided because a string is already loaded at startup, so the user-defined class is unable to load a custom ClassLoader.

The above on the ClassLoader loading mechanism for a general introduction, and then have to explain this another and ClassLoader related classes, that is class class, each ClassLoader loaded class file, Will eventually be referenced by programmers as instances of class classes, we can think of class classes as a template for ordinary classes, the JVM generates corresponding instances based on this template, and is ultimately used by programmers.

We see that there is a static method Forname in class classes, and this method is used to load class as well as the LoadClass method in ClassLoader, but the two are different in their roles.
class<?> loadclass (String name)
Class<?> loadclass (String name, Boolean resolve)
We see the above two method declarations, the second parameter of the second method is to connect the class when it is used to set the load class, true to connect, or not to connect.

When it comes to connections, we have to explain that when the JVM loads the class, it takes three steps to mount, connect, initialize . The load is to find the corresponding class file, read into the JVM, the initialization is needless to say, the most important is the connection.

The connection is divided into three steps, the first step is to verify that class is compliant, the second step is preparation, is to allocate memory for the class variable and set the default initial value, the third step is to explain, and this step is optional, according to the above LoadClass method of the second parameter to determine whether need to explain, the so-called interpretation according to the Deep JVM The definition of this book is to find the corresponding entity based on the symbolic reference in the class, and then replace the symbol reference with a direct reference process. A bit esoteric, oh, this is not to do more explanation, want to learn more about the "Deep JVM bar", oh, and then explain this step-by-step, then do not know when to explain the finished.

Let's take a look at the two-parameter LoadClass method, which is defined in the Java API documentation as protected, which means that the method is protected, and the method the user should really use is the one with the parameter, The LoadClass method of a parameter is actually a method that invokes two arguments, and the second argument defaults to False, so it can be seen here that the class is not interpreted by the LoadClass loading class, and therefore does not initialize the class. The class class of the Forname method is the opposite, the use of forname load when the class is interpreted and initialized, Forname also has a different version of the method, you can set whether to initialize and set the ClassLoader, this is not much to say.


I don't know if the explanation for these two loading methods is clear enough, in this case, such as jdbc DRIVER loading, we are using the JDBC driver when loading the forname rather than the ClassLoader LoadClass method? We know that the JDBC driver is through DriverManager and must be registered in DriverManager, and if the driver class is not initialized, it cannot be registered in DriverManager, so forname must be used instead of loadclass.

By ClassLoader We can customize the ClassLoader, customize the loading mode that we need, such as loading from the network, loading the files from other formats, and so on, in fact, there are many places ClassLoader have not mentioned, For example, some implementations within the ClassLoader, etc.,

   through this article, small series hope that we have some understanding of the classloader  mechanism, thank you for your support!  

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.