Android ClassLoader Parental trust mode

Source: Internet
Author: User

Overview

ClassLoader's Parental trust mode : ClassLoader is divided into three levels: bootstrap ClassLoader (root loader), intermediate level: extension ClassLoader (Extended class loader) the lowest level app ClassLoader (application class loader).

Root (Bootstrap) class loader : The loader does not have a parent loader. It is responsible for loading the virtual machine's core class libraries, such as java.lang.*. For example, Java.lang.Object is loaded by a root loader. The root class loader loads the class library from the folder specified by the System Properties Sun.boot.class.path.

The implementation of the root class loader relies on the underlying operating system. is part of the implementation of the virtual machine, and it does not inherit the Java.lang.ClassLoader class.

Extension (Extension) class loader : Its parent loader is the root class loader. It is loaded into the class library from the folder specified by the Java.ext.dirs system Properties, or from the Jre/lib/ext subfolder (Extension folder) of the JDK's installation folder, assuming that the user-created jar file is placed under this folder and is also loaded by the extended class loader itself. The extended class loader is a pure Java class and is a subclass of the Java.lang.ClassLoader class.

System class Loader : Also known as the Application class loader. Its parent loader is an extension class loader.

It loads the class from the environment variable classpath or the folder specified by the System Properties Java.class.path, which is the default parent loader for the class loader that the user defines.

The System class loader is a pure Java class. is a subclass of the Java.lang.ClassLoader class.


A parent-child loader is not an inheritance relationship. This means that the child loader does not necessarily inherit the parent loader.

For Java, Java virtual machines load the Java class file used by ClassLoader into the JVM memory. And this classloader is bootstrap ClassLoader. For the app, first request the app level to load, then request extension ClassLoader, and finally start Bootstrap ClassLoader.

Define yourself ClassLoader

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqveglhbmd6aglob25noa==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast "alt=" here to write a picture descriptive narrative "title=" ">

 Public  class myclassloader extends ClassLoader {    //class loader name    PrivateString name;//Load the path of the class    PrivateString Path ="d:/";Private FinalString FileType =". Class"; Public Myclassloader(String name) {//Let the System class loader become the parent loader for the class loader        Super(); This. name = name; } Public Myclassloader(ClassLoader parent, String name) {//Displays the parent loader that specifies the class loader        Super(parent); This. name = name; } PublicStringGetPath() {returnPath } Public void SetPath(String Path) { This. Path = path; }@Override     PublicStringtoString() {return  This. Name; }Private byte[]Loaderclassdata(String name) {InputStream is =NULL;byte[] data =NULL; Bytearrayoutputstream BAOs =NewBytearrayoutputstream (); This. Name = This. Name.replace (".","/");Try{is =NewFileInputStream (NewFile (path + name + fileType));intc =0; while(-1! = (c = is.read ())) {baos.write (c);        } data = Baos.tobytearray (); }Catch(Exception e)        {E.printstacktrace (); }finally{Try{Is.close ();            Baos.close (); }Catch(IOException e)            {E.printstacktrace (); }        }returnData }@Override     Publicclass<?

>Findclass(String name) {byte[] data = Loaderclassdata (name);return This. defineclass (name, data,0, data.length); } Public Static void Main(string[] args)throwsClassNotFoundException, Instantiationexception, illegalaccessexception {//loader1 's parent loader is the System class loaderMyclassloader Loader1 =NewMyclassloader ("Loader1"); Loader1.setpath ("d:/lib1/");//loader2 's parent loader is Loader1Myclassloader Loader2 =NewMyclassloader (Loader1,"Loader2"); Loader2.setpath ("d:/lib2/");//loader3 's parent loader is the root class loaderMyclassloader Loader3 =NewMyclassloader (NULL,"Loader3"); Loader3.setpath ("d:/lib3/"); Class clazz = Loader2.loadclass ("Sample"); Object object = Clazz.newinstance (); }} Public class Sample { Public Sample() {System.out.println ("Sample is loaded by"+ This. GetClass (). getClassLoader ());NewA (); }} Public class A { Public A() {System.out.println ("A is loaded by"+ This. GetClass (). getClassLoader ()); }}

Each of its own definition ClassLoader must inherit the abstract class ClassLoader, and each ClassLoader will have a parent ClassLoader. We can take a look at ClassLoader. This abstract class has a getparent () method that returns the parent of the current ClassLoader, noting that the parent does not refer to the inherited class, Instead, a ClassLoader is specified when instantiating the ClassLoader, assuming that the parent is null, then the parent of the ClassLoader is bootstrap Classloade.

The above explains the role of ClassLoader and one of the most important loading processes, and then we say that ClassLoader uses the parental commit mode for class loading.

ClassLoader Parental trust model

In layman's words, a particular class loader trusts the Onboarding task to the parent class loader when it receives a request to load the class. Recursion in turn. Assuming that the parent loader is able to complete the class loading task, it returns successfully, and only the parent loader cannot complete this load task until it loads itself.

In order to better understand the parental trust model, we first define a classloader, assuming that we use this own definition of classloader loaded into java.lang.String, then this is the String will be this classloader load it?

In fact java.lang.String This class is not loaded by our own definition of ClassLoader. It was loaded by bootstrap ClassLoader. This is actually the reason for the Parental trust model, since it would have entrusted its father, ClassLoader, to load it before any one of its own definitions ClassLoader loaded into a class, only to be loaded by himself if the father ClassLoader failed to load the success.

In the example above, since java.lang.String is a class that belongs to the Java Core API, it is loaded with its own defined ClassLoader. The ClassLoader will first entrust its father ClassLoader to load (bootstrap ClassLoader), so it will not be loaded by our own definition of ClassLoader.

Let's take a look at ClassLoader's source code:

protected synchronizedClassLoadClass(String name,BooleanResolvethrowsclassnotfoundexception{//First check whether the class specified by the name has been loadedClass C = findloadedclass (name);if(c = =NULL) {Try{if(Parent! =NULL) {//Assuming that the parent is not NULL, the loadclass of the parent is called to loadc = Parent.loadclass (name,false); }Else{//parent is null, the Bootstrapclassloader is called to loadc = FINDBOOTSTRAPCLASS0 (name); }               }Catch(ClassNotFoundException e) {//Assuming that it still fails to load successfully, call its own findclass to loadc = findclass (name); }           }if(resolve)           {Resolveclass (c); }returnC }
Advantages of using parental trust model

So what are the advantages of using parental trust models?

    1. Because of this, you can avoid repeated loading. When the father has already loaded the class, there is no need for the child classloader to be loaded again.

    2. Considering the security factor, let's imagine that without such a commit model, we can use our own string to dynamically replace the defined type in the Java Core API, which can be a big security risk. The way in which parents are entrusted, it is possible to avoid this situation, because the string has been loaded at startup, so the user's own definition of the class is unable to load a self-defined classloader.

Attached: Android ClassLoader Simple Introduction

Android ClassLoader Parental trust mode

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.