Fully parse the Java class loader

Source: Internet
Author: User

deeply understand and explore the Java class loading mechanism----1.java.lang.classloader Class Introduction

The basic function of the Java.lang.ClassLoader class is to find or generate its corresponding byte code based on the name of a given class, and then define a Java class from those byte codes, which is an instance of the Java.lang.Class class.

ClassLoader provides a series of methods to compare important methods such as:

tree hierarchy of Class loaders in 2.JVM

The ClassLoader in Java can be broadly divided into two categories, one for the system, the other for Java application developers.

Boot class loader (bootstrap class loader):

It is used to load the Java core library (Jre/lib/rt.jar), which is implemented by native C + + code and does not inherit from Java.lang.ClassLoader.

load extension classes and application ClassLoader, and specify their parent class loader, which is not available in Java.  

Extension class loader (Extensions class loader):

It is used to load the Java extension library (Jre/ext/*.jar). The implementation of the Java virtual machine provides an extension library directory. The ClassLoader finds and loads the Java class in this directory.  

Application class loader (Application class loader):

It loads the Java class according to the Classpath (CLASSPATH) of the Java application. In general, Java-applied classes are loaded by it. It can be obtained by Classloader.getsystemclassloader ().

Custom class Loader (loader):

In addition to the system-provided classloader, developers can implement their own classloader by inheriting the Java.lang.ClassLoader class to meet some special requirements.

The following test code can demonstrate this hierarchy:

 public  class   Testclassloader {@Test  public  void   Test () { // application class loader   System.out.println (        Classloader.getsystemclassloader ());  // extensions class loader   System.out.println (Classloader.getsystemclassloader (). GetParent ());  // bootstrap class loader   System.out.println (Classloader.getsystemclassloader (). GetParent (). GetParent ()); }}

The output is:

You can see that the ClassLoader class is loaded by Appclassloader. His father was Extclassloader,extclassloader's father. Cannot get it because it is implemented in C + +.

3. Parental delegation mechanism

When a particular class loader receives a request to load a class, it first gives the load task delegate to the parent ClassLoader, and the parent class loader then delegates the load task up to the parent ClassLoader, and if the parent class loader can complete the class load task, it returns successfully, and if not, the delegate task is passed down. Loaded by its sub-class loader.

Benefits of parental delegation mechanisms:

ensure the security of the Java Core Library (for example, if the user writes a java.lang.String class by itself, the parent delegation mechanism cannot be loaded and does not break the load of the native string class)

Proxy mode

In contrast to the parent delegation mechanism, the proxy mode is the first attempt to load itself, and if it fails to load, it is passed up. Tomcat is the proxy mode.

4. Custom class Loaders
 Public classMyclassloaderextendsclassloader{PrivateString RootPath;  PublicMyclassloader (String rootpath) { This. RootPath =RootPath; } @OverrideprotectedClass<?> Findclass (String name)throwsClassNotFoundException {//The check if the class has been loadedclass<?> C =Findloadedclass (name); if(c!=NULL){            returnC; }        //load the class        byte[] Classdata =getclassdata (name); if(classdata==NULL){            Throw Newclassnotfoundexception (); }        Else{C= DefineClass (name,classdata, 0, classdata.length); returnC; }        }        Private byte[] Getclassdata (String className) {string path= rootpath+ "/" +classname.replace ('. ', '/') + ". Class"; InputStream is=NULL; Bytearrayoutputstream Bos=NULL; Try{ is=NewFileInputStream (path); Bos=NewBytearrayoutputstream (); byte[] buffer =New byte[1024]; inttemp = 0;  while(temp = is.read (buffer))!=-1) {bos.write (buffer,0, temp); }            returnBos.tobytearray (); } Catch(Exception e) {e.printstacktrace (); }finally{            Try{is.close ();            Bos.close (); } Catch(Exception e) {e.printstacktrace (); }                    }                return NULL; }    }

To test a custom class loader

Create a test class HelloWorld

 Package testothers;  Public class HelloWorld {}

Create a Testothers folder in the D packing directory, compile the Helloworld.java, and place the resulting class file under the Testothers folder.

Test with the following code

 Public class Testmyclassloader {    @Test    publicvoidthrows  exception{         New Myclassloader ("D:");        Class<?> C = Loader.loadclass ("Testothers.helloworld");        System.out.println (C.getclassloader ());}    }

Output:

Description the HelloWorld class was loaded by our custom class loader Myclassloader

5. The class loading process is detailed

The JVM divides the class loading process into three steps: Load (load), link, and Initialize (Initialize)

1) load :

Find and load the binary data of the class;

2) links :

Validation: Ensure that the loaded class information complies with the JVM specification and does not have security issues.

Prepare: Allocates memory for static variables of the class and initializes it to the default value.

Parse: Converts a symbolic reference in a virtual machine constant pool to a direct reference.

3) Initialize :

Assigns the correct initial value to the static variable of the class.

PS: The parsing section needs to illustrate that in Java, the virtual opportunity to maintain a constant pool for each loaded class is "different from the string constant pool, which is just an ordered collection of literal values (such as class names, method names) and symbol references for that class. The string constant pool, which is shared by the entire JVM, is a symbol reference, such as int a = 5, and the parsing process converts it to the relative address of the object's address in the heap.

Initialization steps for the class:

1) If this class has not been loaded and linked, then load and link it first

2) If the class has a direct parent class, and the class has not been initialized (note: In a classloader, the class can only be initialized once), then initialize the immediate parent class (not for the interface)

3) if a block with a static identity exists in the class, then these initialization statements are executed sequentially.

Fully parse the Java class loader

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.