1, the JDK default provides the following three kinds of ClassLoader:
- BootStrap ClassLoader: called the Startup class loader, C + + achieved, is the topmost class loader in the Java class load hierarchy ( initialized after JVM startup ) , is responsible for loading the JDK core class library, such as: Rt.jar, Resources.jar, Charsets.jar, etc.;
- Extensionclassloader: called the Extension class loader, is responsible for loading the Java Extension Class library, all jars under java_home/jre/lib/ext/are loaded by default . The loader is implemented in Java and is loaded by Bootstrploader Extclassloader, And the Extclassloader's parent loader is set to BOOTSTRP loader;
- Appclassloader: Called the system ClassLoader, is responsible for loading all the jar and class files in the application Classpath directory .
Note: In addition to these three types, the JDK allows the custom classloader to be customized;
2. Parent Assignment:
ClassLoader uses a parent-delegate model to search for classes, and each ClassLoader instance has a reference to the class loader (not an inherited relationship, which is a contained relationship). The virtual machine's built-in ClassLoader (Bootstrapclassloader) 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 tries to check from the bottom up ( Check the parent classloader ) that the class has been loaded , if an loader has already loaded the class, return the class object directly until bootstrapClassLoader. the class is then loaded from top to bottom , first by the topmost class loader bootstrapclassloader, and if not loaded, the task is forwarded to extension ClassLoader attempts to load, and if it is not loaded, it is forwarded to Appclassloader for loading, and if it is not loaded, it is returned to the initiator of the delegate, which loads the class in a URL such as the specified file system or network. If none of them are loaded into this class, the ClassNotFoundException exception is thrown.
1) 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 (Bootstrcpclassloader) at startup, the user-defined ClassLoader can never load a string of its own writing, Unless you change the default algorithm for the ClassLoader search class in the JDK.
2) The JVM determines whether the two class is 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.
3. Custom ClassLoader:To customize ClassLoader we need to inherit the Java.lang.ClassLoader class. There are several important methods in this class, but if you want to follow the parental delegation mechanism, you only need to override the findclass method; If you want to change parental delegation, rewrite loadclass method.
Example:
0, customize a class, in the Tomcat Webapps/root directory, set up a good class package structure, and then put the class compiled classes into it; package Classload;public class Test {public static void Main (string[] args) {}public String getstr () {System.out.println ("Ceshi ..."); return "Ceshi";}} 1. Custom class Loader package Classload;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.url;public class Networkclassloader extends Classloader{private String rootUrl;// Http://localhost:8090/Test.classpublic Networkclassloader (String rooturl) {super (); this.rooturl = Rooturl;} @Overrideprotected class<?> Findclass (String name) throws ClassNotFoundException {Class clazz = Null;//thi S.findloadedclass (name); The parent class has loaded//if (clazz = = null) {//check if the class has been loaded byte[] Classdata = getclassdata (name); According to the binary name of the class, obtain the byte-code array of the class file if (Classdata = = null) {throw new ClassNotFoundException (); } clazz = defineclass (name, Classdata, 0, classdata.length); //Convert class bytecode array to class class instance//} return clazz; } private byte[] Getclassdata (String name) {InputStream is = null; try {String path = Classnametopath (name); URL url = new URL (path); byte[] buff = new BYTE[1024*4]; int len =-1; is = Url.openstream (); Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); while (len = is.read (buff))! =-1) {baos.write (Buff,0,len); } return Baos.tobytearray (); } catch (Exception e) {e.printstacktrace (); } finally {if (is = null) {try {is.close (); } catch (IOException e) {e.printstacktrace (); }}} return null; } private String Classnametopath (string name) {return rooturl + "/" + Name.replace (".","/") +". Class "; }}3, test class: Package Classload;public class Classloadertest {/** * @param args */public static void main (string[] args) {try {/*classloader loader = ClassLoaderTest.class.getClassLoader (); Get the class loader for this class classloadertest while (loader! = null) {SYSTEM.OUT.PRINTLN (loader); Loader = Loader.getparent (); Obtain a reference to the parent loader} System.out.println (loader); */String Rooturl = "http:// Localhost:8090/"; Networkclassloader Networkclassloader = new Networkclassloader (Rooturl); String classname = "Classload.test"; Class clazz = Networkclassloader.loadclass (classname); System.out.println (Clazz.getclassloader ()); Print class loader Object newinstance = Clazz.newinstance (); Clazz.getmethod ("Getstr"). Invoke (Newinstance); Call method} catch (Exception e) {e.printstacktrace (); }}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Custom ClassLoader: Loading class from the Web into memory, instantiating methods in the call