ClassLoader principle of "Java core" and its use

Source: Internet
Author: User
Tags class definition

Again the skin of the blog for Change, looking more concise comfortable some. The first part of the knowledge is only a little understand, take it can be used, but their own aesthetic and design level limited, it is difficult to make their own special satisfaction of things, but also a small regret it! Anyway, because recently involved in the Java core is a lot of things, I think it was just an application level, just consider the project progress, as well as the realization of customer requirements, their own technical bills are too much, look at the garden and my age people in different aspects have a relatively deep research, but also seems to be in the fur stage , very frightened, now every day is difficult to sleep! Today, the Java Core Knowledge, ClassLoader principle and its application to make a simple summary.

First, what is ClassLoader?

After we've written a Java program, it's not a CS or BS application, is a complete Java application organized by several. class files, when the program is run, it calls an entry function of the program to invoke the relevant functions of the system, and these functions are encapsulated in different class files, so it is often necessary to call from this class file another class file method, a system exception is thrown if the other file does not exist. When the program starts, it does not load all the class files used by the program at once, but instead dynamically loads a class file into memory according to the needs of the program through the Java class loading mechanism (ClassLoader), so that only the class file is loaded into memory To be referenced by the other class. So ClassLoader is used to dynamically load class files into memory.

Second, the Java default provides three ClassLoader

1.BootStrap ClassLoader: Called the startup ClassLoader, is the topmost class loader in the Java class loading hierarchy and is responsible for loading the core class libraries in the JDK, such as: Rt.jar, Resources.jar, Charsets.jar, etc. , can be obtained by the following program where the loader loaded the relevant jar or class file:

        url[] URLs = sun.misc.Launcher.getBootstrapClassPath (). Geturls ();            for (int0; i < urls.length; i++) {              System.  out . println (Urls[i].toexternalform ());          }

The files obtained are as follows:


2.Extension ClassLoader: called the Extension class loader, is responsible for loading the Java Extension Class library, loading all the jars under java_home/jre/lib/ext/by default.

3.App ClassLoader: Called the system ClassLoader, is responsible for loading all jar and class files in the application Classpath directory.

Note: In addition to the three classloader provided by the Java default, users can also define their own classloader as needed. These custom classloader must inherit from the Java.lang.ClassLoader class, as well as the additional two classloader provided by Java (Extension ClassLoader and app ClassLoader), but Bootstrap ClassLoader does not inherit from ClassLoader, because it is not an ordinary Java class, the underlying is written in C + +, embedded in the JVM kernel, when the JVM starts, Bootstrap ClassLoader also with the boot, responsible for loading the core class library, and constructs the extension ClassLoader and the app ClassLoader class loader.

Three, the principle of ClassLoader loading class

1. Introduction of principle

ClassLoader uses a parent- delegate model to search for classes, and each ClassLoader instance has a reference to the ClassLoader (not an inherited relationship, a contained relationship), and the virtual machine's built-in ClassLoader (Bootstrap ClassLoader) itself does not have a parent classloader, but can be used as a parent ClassLoader for other ClassLoader instances. When a ClassLoader instance needs to load a class, it attempts to search for a class by itself, delegating the task to its parent classloader, which is checked from top to bottom, first by the topmost class loader bootstrap classloader trying to load, If not loaded, the task is forwarded to the extension ClassLoader attempt to load, if not loaded, then to the app ClassLoader to load, if it is not loaded, then return to the initiator of the delegate, It loads the class into a URL such as a specified file system or network. If none of them are loaded into this class, the ClassNotFoundException exception is thrown. Otherwise, the found class generates a class definition, loads it into memory, and finally returns the class instance object in memory.

2. Why use parents to entrust this model?

Because this avoids repeated loading, there is no need for the child classloader to load again when the parent has loaded the class. Considering the security factors, let's imagine that if we don't use this delegate pattern, we can use a custom string at any time to dynamically replace the type defined in the Java Core API, so there's a very big security risk, and the way that parents delegate, you can avoid this situation, Because the string has been loaded by the Boot class loader (BOOTSTRCP ClassLoader) at startup, the user-defined ClassLoader can never load a string that he writes, Unless you change the default algorithm for the ClassLoader search class in the JDK.

3, but the JVM in the search class, and how to determine the two class is the same?

The JVM determines whether the two classes are the same, not only to determine whether the two class names are the same, but also to determine whether the same class loader instance is loaded. The JVM considers the two classes to be the same only if the two are both satisfied. Even if the two class is the same class bytecode, if it is loaded by two different ClassLoader instances, the JVM will consider them to be two different classes. such as a Java class on the network Org.classloader.simple.netclassloadersimple,javac compiled after the generation of bytecode files Netclassloadersimple.class,classloadera and Classloa Derb these two classloader and read the Netclassloadersimple.class file and define the Java.lang.Class instance to represent this class, for the JVM, they are two different instance objects, but they are really the same byte-code file, if you try to put this CLA When a SS instance generates a specific object for conversion, it throws a run-time exception java.lang.ClassCaseException, suggesting that it is two different types. Now use the example to verify that the above description is correct:

1), build a class on the Web server

 Package org.classloader.simple;  Public class netclassloadersimple {        private  netclassloadersimple instance;      Public void setnetclassloadersimple (Object obj) {        this. Instance= (netclassloadersimple) obj;    }} 

The Setnetclassloadersimple method of the Rg.classloader.simple.NetClassLoaderSimple class receives an object type argument and casts it to Org.classloader.simple.NetCla The ssloadersimple type.

2), test two class is the same

 PackageClassLoader; Public classNewworkclassloadertest { Public Static voidMain (string[] args) {Try {            //test Load class files in the networkString Rooturl = "Http://localhost:8080/httpweb/classes"; String ClassName= "Org.classloader.simple.NetClassLoaderSimple"; Networkclassloader NCL1=NewNetworkclassloader (Rooturl); Networkclassloader Ncl2=NewNetworkclassloader (Rooturl); Class<?> CLAZZ1 =Ncl1.loadclass (className); Class<?> CLAZZ2 =Ncl2.loadclass (className); Object obj1=clazz1.newinstance (); Object Obj2=clazz2.newinstance (); Clazz1.getmethod ("Setnetclassloadersimple", Object.class). Invoke (Obj1, obj2); } Catch(Exception e) {e.printstacktrace (); }    }    }

First get the binary name of a class file on the network, and then create two instances from the custom ClassLoader Networkclassloader, and load the class separately based on the network address. Then we get the class instance clazz1 and CLAZZ2 generated by these two ClassLoader instances, and finally generate the concrete instance object Obj1 and Obj2 for each of the two class instances, The Setnetclassloadersimple method in Clazz1 is then called through reflection.

3), test results

Conclusion: It can be seen from the results that although the same class bytecode file is loaded by two different ClassLoader instances, the JVM considers them to be two different classes.

ClassLoader principle of "Java core" and its use

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: 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.