How the Java ClassLoader works

Source: Internet
Author: User

the Java ClassLoader is used at run time Loading class (*.class file). the Java class loader is based on three principles: delegate, Visibility, uniqueness. The delegation principle forwards the request of the load class to the parent ClassLoader , and only loads the class when the parent ClassLoader cannot find or load the class. The visibility principle allows the subclass loader to view all classes loaded by the parent class loader, but the parent ClassLoader cannot see the classes loaded by the child ClassLoader. The uniqueness principle allows only one class file to be loaded, which is basically done by the delegation principle and ensures that the subclass loader does not reload classes that were loaded by the parent ClassLoader. The correct understanding of the ClassLoader principle must address issues like Noclassdeffounderror in Java, java.lang.ClassNotFoundException (these phenomena are related to loading classes). The class loader is also an important topic in advanced Java interviewing, where the knowledge of how ClassLoader and Classpath works is expected by Java programmers. I often encounter this problem in various Java interviews: Can a class be loaded by two different classloader in Java? In this article, we'll learn what a classloader is in Java, how it works, and some of the details associated with it.

What is the class loader for Java?

the class loader in Java is a class that loads Java class files (*.class). Java code is compiled by the Javac compiler into a class file as bytecode, and the JVM (Java Virtual machine) executes the Java program by manipulating the bytecode in the class file. The class loader is responsible for loading class files from the file system, network, or any other resource. The default class loader used in Java has the following three types:Bootstrap, Extensionas wellSystem or application class loader. Each classloader has a predefined location where they load the class file. Bootstrapthe class loader is responsible for theRt.jarLoaded instandard JDK class files, and it is the parent of all class loaders in Java. BootstrapThe ClassLoader does not have any parent, if you callString.class.getClassLoader ()NULL is returned and the associated code throws a null pointer exception. Bootstrapthe class loader is also known in Java asPrimordial ClassLoader(Native class loader). Extensionthe class loader delegates its parentBootstrapclass loader to load class files, if the delegate fails, from pointing to theJava.ext.dirsof System PropertiesJre/lib/extdirectory or any other directory to load the class file. JVMin theExtensionThe class loader isSun.misc.LauNcher$extclassloaderimplementation. JVMthe third type of default class loader used isSystem or Applicationclass Loader, it is primarily responsible for theCLASSPATHThe environment variable loads the application-specific class file,-classpath the OR-CP command-line option, and the Classpath property of the jar internal manifest file. Applicationthe class loader isExtensionthe class loader's children, which are represented by theSun.misc.launcher$appclassloaderclass Implementation. Moreover, in addition toBootstrapclass loader (mostly byClanguage Implementation, all Java ClassLoader are implemented using Java.lang.ClassLoader.

In short, these three kinds of loader load class files have the following paths:

1) Bootstrap Classloader-jre/lib/rt.jar

2) Extension Classloader-jre/lib/ext or any point to Java.ext.dirs the path

3) Application ClassLoader - CLASSPATH environment variables,-classpath OR-CP command-line options,

The Classpath property of the jar internal manifest file

How the Java ClassLoader works

as I described earlier, the Java class loader is based on three principles: delegate, visibility, uniqueness. In this section we will look at the details of these principles and how the Java ClassLoader works by example. Incidentally, here is a diagram that explains how to load a class file in Java by using the delegate ClassLoader.

Principle of entrustment

when discussing the question of when a class file in Java is loaded and initialized, the class file in Java is loaded when it is needed. Suppose you have an Application-specific class file called Abc.class, and the first request to load the class file is sent to the application class loader. the application class loader delegates its parent Extension class loader, and the Extension class loader delegates to the the Bootstrap class loader. the Bootstrap class loader looks for the class file in Rt.jar , and the request is forwarded to the Extension because it is not found class loader. the Extension class loader looks for the class file in the jre/lib/ext directory and attempts to load the class file, if the class file is found, then The Extension class loader will load the class file (theapplication class loader will never load the class file), but if Extension the class loader does not load the class file, the application class loader will load the class file from the Java classpath. Note: The classpath is used to load the class file, and the path is used to find the executable command like Javac or Java.

The principle of visibility

depending on the visibility principle, the child classloader can see the class file loaded by the parent class loader, but not in turn. This means that if the application class loader loads the abc.class file, try using Extension class loader to load the abc.class file, an exception java.lang.ClassNotFoundExceptionis thrown. Take a look at the following example:

Packagetest;

Java code
  1. Importjava.util.logging.Level;
  2. Importjava.util.logging.Logger;
  3. /**
  4. * Java program to demonstrate what ClassLoader works in Java,
  5. * In particular about visibilityprinciple of ClassLoader.
  6. *
  7. * @author Javin Paul
  8.  */   
  9. Public class classloadertest {
  10. Public static void main (String args[]) {
  11. Try {  
  12. //printingclassloader of this class   
  13. System.out.println ("Classloadertest.getclass (). getClassLoader ():"
  14. + Classloadertest. class  . getClassLoader ());
  15. //tryingto explicitly load this class again using Extension class loader   
  16. Class.forName ("test. Classloadertest ",true
  17. , Classloadertest. class  . getClassLoader (). GetParent ());
  18. }catch(Classnotfoundexceptionex) {
  19. Logger.getlogger (classloadertest.   Class. GetName ()). log (level.severe,null, ex);
  20. }
  21. }
  22. }



Output:

Java code
  1. Classloadertest.getclass (). getClassLoader (): Sun.misc.launcher$appclassloader @601bb1   
  2. - / , / 20122 : + : - AM test. Classloadertestmain
  3. SEVERE: null
  4. Java.lang.ClassNotFoundException:test. Classloadertest
  5. At java.net.urlclassloader$1. Run (URLClassLoader.java:202)
  6. At Java.security.AccessController.doPrivileged (Nativemethod)
  7. At Java.net.URLClassLoader.findClass (URLClassLoader.java:)
  8. At Sun.misc.launcher$extclassloader.findclass (Launcher.java:229)
  9. At Java.lang.ClassLoader.loadClass (Classloader.java:306)
  10. At Java.lang.ClassLoader.loadClass (Classloader.java:247)
  11. At JAVA.LANG.CLASS.FORNAME0 (Nativemethod)
  12. At Java.lang.Class.forName (Class.java:247)
  13. At Test. Classloadertest.main (Classloadertest.java:)

The principle of uniqueness

According to this principle, when a class file is loaded by the parent class loader, the child classloader cannot load it. While it is entirely possible to write a class loader that loads the class file itself, this violates the principle of delegation and uniqueness, and there is no benefit in doing so. When you write your own classloader, you should follow all the ClassLoader principles.

How to load classes accurately in Java
Java provides APIs to explicitly load a class by Class.forName (classname) and Class.forName (classname, initialized, ClassLoader) methods, Remember the way JDBC is used to load the JDBC driver, which is the mechanism used to load the corresponding class. As we have shown in the example above, you can pass in the name of the loader that loads a particular class with the same binary name as parameters. Class is called by the LoadClass () method of Java.lang.ClassLoader, which in turn calls the Findclass () method to find the corresponding bytecode for the corresponding class. In this example, the extension ClassLoader uses Java.lang.URLClassLoader to look up class files and resources in jar packages and directories. where all the "/" ends of the query are treated as directories. If the Findclass () method does not find the related class, it throws a Java.lang.ClassNotFoundException exception, and if the method finds the related class, it calls DefineClass () method to convert the bytecode to an instance of the. Class and return the instance to the caller.

In Java, inwhichThe class loader is used in the
The ClassLoader is a powerful concept in Java and is used in many places. One of the more popular examples is the Appletclassloader class loader that is used to load classes in applets, because applets are loaded from the Internet rather than from the local file system. By using a separate class loader, you can load multiple identical classes from several different resources, and these classes are treated as different classes in the JVM. The Java EE uses different classloader to load classes from different locations, such as the classes in a war package are loaded through the Web-app class loader, while classes bound in the Ejb-jar package are loaded with other classloader. Some Web servers also support the thermal deployment feature, which is achieved by implementing ClassLoader. You can also use ClassLoader to load classes from a database or other persisted storage system.
This is all about the ClassLoader in Java and how it works. We have seen the principles of delegation, visibility, and uniqueness, which are important for debugging code or for solving problems related to ClassLoader in Java. In summary, the ClassLoader works on every developer and architect who designs Java applications and packages.

1. This article is a translation of the Programmer's architecture

2. This article is translated from http://javarevisited.blogspot.com/2012/12/how-classloader-works-in-java.html?m=1

3. Reprint Please be sure to indicate this article from : Programmer Architecture (No.:archleaner )

4. More articles please scan the code:

How the Java ClassLoader works

Related Article

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.