An in-depth study of Java class loading mechanism

Source: Internet
Author: User

Class loading mechanism

Class loading is the first step in the Java program, and studying the load of the class can help to understand the JVM execution process, and instruct the developer to take more effective action to cooperate with the program execution, while allowing the program to dynamically control class loading, such as hot deployment, to improve the flexibility and adaptability of the program.

Class loading process

The place where the Java program runs is memory.
When executing Java HelloWorld at the command line, the JVM loads Helloworld.class into memory to form a class object: Helloworld.class, as follows:
1. Locate the JRE directory, locate the Jvm.dll file, and initialize the JVM
2. Generate a bootstrap Loader (bootloader, lightweight application that defines the classes that you want to share between applications)
3.Bootstrap Loader automatically loads extended Loader (Standard extension class loader) and sets its parent Loader to Bootstrap Loader
4.Bootstrap Loader automatically loads the Appclass Loader (System class loader) and sets its parent Loader to extended Loader.
5. Finally loaded by Appclass loader HelloWorld class
Bootstrap loader-->extended Loader-->appclass Loader
The above is the most general process of class loading.

Directories that the class loader searches for separately

1. Bootstrap Loader (startup ClassLoader): Loads the path or jar specified by the System.getproperty ("Sun.boot.class.path").

2, Extended Loader (Standard extension class loader Extclassloader): Loads the path or jar specified by System.getproperty ("Java.ext.dirs"). When you run a program using Java, you can also specify its search path, for example: Java-djava.ext.dirs=d:\projects\testproj\classes HelloWorld

3. Appclass Loader (System ClassLoader Appclassloader): Loads the path or jar specified by System.getproperty ("Java.class.path"). When using Java to run a program, you can also add-CP to overwrite the original classpath settings, for example: JAVA-CP./lavasoft/classes HelloWorld

Extclassloader and Appclassloader after the JVM is started, a copy is saved in the JVM, and the search path cannot be changed while the program is running. If you want to load a class from another search path at run time, a new classloader will be generated.

Features of the class loader

1. When running a program, the specified class is always loaded by the Appclass Loader (System class loader).
2. When the class is loaded, each classloader will hand the load task to its parent, if the parent cannot find it, and then load it by itself.
3, Bootstrap Loader (startup class loader) is the top class loader, and its parent loader is null.

The class loader gets

Look at the following example

publicclass HelloWorldClass {    publicstaticvoidmain(String[] args) {        new HelloWorldClass();        Class c= hello.getClass();        ClassLoader loader = c.getClassLoader();        System.out.println("loader:"+loader);        System.out.println("loader.getParent():"+loader.getParent());        System.out.println("loader.getParent().getParent():"+loader.getParent().getParent());    }}

Operation Result:

loader:sun.misc.Launcher$AppClassLoader@47415dbfloader.getParent():sun.misc.Launcher$ExtClassLoader@1471cb25loader.getParent().getParent():null

As can be seen from the above results, it is not obtained to Extclassloader's parent Loader, because Bootstrap Loader (startup ClassLoader) is implemented in C language, cannot find a definite way to return the parent Loader, then returns NULL.

Loading of classes

There are three ways to load a class:
1. When the command line starts the application, it is loaded by the JVM initialization
2. Dynamic loading via Class.forName () method
3. Dynamic loading via Classloader.loadclass () method
Three ways to distinguish between the larger, see an example to understand:

 Public classHelloWorld { Public Static void Main(string[] args) throws ClassNotFoundException {ClassLoader loader = HelloWorld.class.getClassLoader (); System. out. println (loader);//Use Classloader.loadclass () to load the class without executing the initialization blockLoader.loadclass ("Test2");//using Class.forName () to load the class, the initialization block is executed by default//Class.forName ("Test2");                //Use Class.forName () to load the class and specify ClassLoader, which does not perform static block initialization//Class.forName ("Test2", false, loader);} } Public classTest2 {Static{System. out. println ("Static initialization blocks are executed!" "); } }

Switch the loading mode separately, there will be different output results.

Custom ClassLoader

To illustrate the problem, let's look at the example:

 PackageTestImportJava.net.MalformedURLException;ImportJava.net.URL;ImportJava.net.URLClassLoader;/** * Customize ClassLoader * * * *  Public  class myclassloader {     Public Static void Main(string[] args)throwsMalformedurlexception, ClassNotFoundException, Illegalaccessexception, instantiationexception { URL url =NewURL ("File:/e:\\projects\\testscanner\\out\\production\\testscanner"); ClassLoader Myloader =NewURLClassLoader (Newurl[] {URL}); Class C = Myloader.loadclass ("Test. Test3 "); System.out.println ("----------");    Test3 t3 = (Test3) c.newinstance (); }} Public  class Test3 {    Static{System.out.println ("The static initialization blocks of the TEST3 are executed!" "); }}
After running:

Static initialization blocks of TEST3 are executed!

Process finished with exit code 0

You can see that the custom ClassLoader Myloader = new URLClassLoader (New Url[]{url}) has successfully loaded the class Test3 into memory and constructed the object Test3 t3 = (TEST3) through the default constructor method C.newinstance ();

There is also an important point about ClassLoader:
The same ClassLoader loaded class file with only one class instance. However, if the same class file is loaded with a different classloader, there will be two different ClassLoader instances (provided that two classloader cannot be used with the same parent class loader).

Reference:
1.love_javc_you's column: In-depth study of Java class loading mechanism
2.SYSU_2010 's Column: BootStrap Loader

Copyright NOTICE: This article for csdn Bo Master lunatictwo original article, without Bo Master permission not reproduced.

An in-depth study of Java class loading mechanism

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.