Java class Loader

Source: Internet
Author: User

The Java class loader can dynamically load Java classes into the JVM, which is part of the JRE, and each Java class must be loaded through a class loader. With the ClassLoader, the Java runtime system can load class files through the ClassLoader, so that no direct access to files or file systems is required. In general, developers do not need to use the class loader directly, but understand the rules and usage of the ClassLoader, It helps to understand the principle of web container implementation and how to deal with ClassNotFoundException and noclassdeffounderror to provide more problem-solving ideas. class Loader hierarchy schemaEach classloader has a parent classloader (except the boot class loader), which is divided into four class loaders (bootstrap class loader): The JAVA class library that directs the ClassLoader to load the core (<java_home>/jre/lib directory), this classloader is the topmost class loader without the parent ClassLoader, which is implemented by the native method. Extension class loader (extension class loader): The extension class loader is loaded with an extension class (<java_home>/jre/lib/ext directory, or a system attribute java.ext.dirs the specified directory), and its implementation isSun.misc.launcher$extclassloaderclass System Class loader (System class loader): The class loader loads files under the Classpath directory, meaning that the generic application-created class is loaded by the system ClassLoader, and its implementation is sun.misc.launcher$ Appclassloader class. Custom Loaders: You can implement a custom class loader by inheriting Java.lang.ClassLoader.

The four load relationships are that the boot ClassLoader is the parent classloader for the extension classloader, and the extension ClassLoader is the parent ClassLoader for the system class loading. The parent loader of the custom loader may be another custom loader or the system ClassLoader, and the default parent ClassLoader for the custom ClassLoader is the System class loader. Their relationship. the delegate mechanism of the class loaderWhen a class loader loads a class, it is loaded first through its parent class loader, and if the parent ClassLoader cannot be loaded, it will load itself. That is, if ClassLoader A is a custom loader, and A's parent class loader is the system ClassLoader. When a loads a class B, it will first delegate the system ClassLoader to load Class B, and the system ClassLoader will delegate the extension class loader, and the extension class loader will delegate the Bootstrap class loader. This creates a delegate mechanism for the ClassLoader. So where is the benefit of this delegation mechanism? First, the JVM identifies a class based on the class loader and the class name. That is, different class loaders load the same class names, and in the JVM's eyes, they are not the same class. There is a problem, if there is no delegation mechanism, and this time there is a custom loader a,a loaded java.lang.String. There is also a custom loader b,b loaded with java.lang.String. At this time, because there are two different types of java.lang.String. If the former new object is assigned to the latter's class reference, the type conversion exception will occur. The delegation mechanism solves this problem, and the core classes like string are only loaded by the bootstrap ClassLoader. How to customize the class loaderGenerally the custom ClassLoader first inherits the Java.lang.ClassLoader class and then overrides its Findclass method. In general, when we use ClassLoader, we call his LoadClass method, as follows:?
protected synchronizedClass loadclass (String name,Booleanresolve)throwsClassNotFoundException {//First , check if the class has already been loadedClass C =Findloadedclass (name); if(c = =NULL) {       Try {       if(Parent! =NULL) {C= Parent.loadclass (Name,false); } Else{C=FINDBOOTSTRAPCLASS0 (name); }       } Catch(ClassNotFoundException e) {//If still not found, then invoke Findclass in order//To find the class.c =Findclass (name); }   }   if(Resolve) {resolveclass (c); }   returnC; }

It is clear from the code that the LoadClass method will first call the Findloadedclass method, which will first find out if the class loader has already loaded it, and if it is already loaded, return the class directly. If the LoadClass method of the parent ClassLoader is called without loading, the Findclass method is called if the class cannot be successfully loaded, and the class loader's delegation mechanism is implemented by this method. The following is a simple custom class loader. Reads the. class file according to the specified path, then translates it into a binary array, and then uses DefineClass to load the class file. Can you see that the final load class is the DefineClass method?
 Public classFilesystemclassloaderextendsClassLoader {PrivateString RootDir;  PublicFilesystemclassloader (String rootdir) { This. RootDir =RootDir; }     protectedClass<?> Findclass (String name)throwsClassNotFoundException {byte[] Classdata =getclassdata (name); if(Classdata = =NULL) {            Throw Newclassnotfoundexception (); }        Else {            returnDefineClass (name, Classdata, 0, classdata.length); }    }     Private byte[] Getclassdata (String className) {string path=Classnametopath (className); Try{InputStream ins=NewFileInputStream (path); Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); intBufferSize = 4096; byte[] buffer =New byte[buffersize]; intBytesnumread = 0;  while((Bytesnumread = ins.read (buffer))! =-1) {baos.write (buffer,0, Bytesnumread); }            returnBaos.tobytearray (); } Catch(IOException e) {e.printstacktrace (); }        return NULL; }     Privatestring Classnametopath (String className) {returnRootDir +File.separatorchar+ classname.replace ('. ', File.separatorchar) + ". Class"; }}

thread Context class loaderThe thread context ClassLoader is typically used in frames. Each thread has a context class loader (unless the thread was created by a local method). You can set the thread's context thread through the Thread.setcontextclassloader () method, and if you do not call this method by constructing a method, then the thread inherits the context class loader of his parent thread. The default class loader for threads is the system class loader. In such a case, the parent loader needs to use a subclass loader, and the delegation mechanism will not take effect at this time. The delegate mechanism can delegate only the parent class loader and cannot delegate the subclass loader. This time it can be loaded by the context class loader. Is such an example in the newinstance of javax.xml.parsers.SAXParserFactory?
 Public Staticsaxparserfactory newinstance () {Try {         return(saxparserfactory) factoryfinder.find (/*The default property, name according to the JAXP spec*/"Javax.xml.parsers.SAXParserFactory",             /*The fallback implementation class name*/"Com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl"); } Catch(Factoryfinder.configurationerror e) {Throw NewFactoryconfigurationerror (E.getexception (), E.getmessage ()); } }

The Newinstance () method creates a SAXParserFactory class, saxparserfactory the implementation of the current ClassLoader is the Boot class loader, But SAXParserFactory implementation class Com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl boot class loader does not load, this time can be used to the thread context class loader. In the above source code, the thread class context loader is seen in the Getproviderclass () method in the Newinstance () method in Factoryfinder.find ().

Java class Loader

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.