ClassLoader simple tutorial

ClassLoader Tutorial

1 Introduction

Classloader central role is to load the class files compiled after the jvm to run the memory of them. Among the jvm specification, the class loader divided into three types:

Bootstrap class loader (BootClassLoader)

Extension class loader (ExtClassLoader)

System class loader (the AppClassLoader)

2. Classification loader

2.1 bootstrap class loader

Bootstrap class loader loads the main class is itself jdk library (JAVA_HOME \ jar file in the lib directory), these libraries are jdk core class libraries (rt.jar), and most importantly, so that the load It is to complete the loading and initialization. And the loader is using the C language.

2.2 extension classloader

Extension class loader is the main lease jar file (JAVA_HOME \ lib \ ext heads jar file) to load the jdk extension package, these files are expanded JDK class library.

2.3 system class loader

System a central role loader is loading class files in the classpath and jar files, these libraries are usually written by the developers themselves, so these classes are finished loading by the system class loader.

3. Delegation Model

In the implementation class loading, first started by the system class loader, but it will be loaded to the implementation of the right to extend the class loader, and similarly, the extension class loader will load the execution to the boot class loader is ultimately begin loaded by the bootstrap class loader, if you need to load the library is not loaded by the bootstrap class category, it will return the right to load the extension class loader. Also, if the library is not the category extension class loader loaded, and finally handed over to the system class loader to complete, this process is commissioned. The purpose of room to do so in order to ensure safety when loading system libraries, such as: Object, String class, etc., which should be completed by the bootstrap class loader, should not be handed over to other class loaders, because if these classes after the library loads can be operated by a user, it can lead to unsafe class. For example: the user can override or modify class methods, it is absolutely prohibited.

Delegation Model:

 

The common API 4. ClassLoader

In addition to the boot class loader is implemented in C language, other class loader ClassLoader inherit from this class, this class provides the corresponding API loading as well as to complete the First class loading and initialization of the parsing process.

API Explanation
getParent() Obtaining a class loader on the
loadClass(String name) Name for the name of the class is loaded, returns a Class example, in this process will be an indirect method of calling findClass
findClass(String name) Name for the name of the class is loaded, it returns an instance of Class. Normally custom class loader will override this method.
findLoadedClass(String name) Check the name for the Class name is already loaded before, it returns a Class instance, if the Class is null, it means not loaded, or is already loaded
defineClass(String name, byte[] b, int off, int len) B converts the binary data byte array to a Class object in Java
resolveClass(Class c) Analytical and connect to the specified Class

2. a custom class loader

We can also custom class loader, you only need to inherit ClassLoader, findClass usually need to override the parent class method. It should be noted that the custom class loader it on a class loader is AppClassLoader, will follow the pattern of the delegate.

Example:

class DemoClassLoader the extends ClassLoader {public 
    / ** 
     * classloader root path 
     * / 
    Private String loadRootPath; 

    public DemoClassLoader (String loadRootPath) { 
        this.loadRootPath = loadRootPath; 
    } 

    / ** 
     * findClass override the parent class 
     * @param name to load the full class name 
     * @return 
     * @throws a ClassNotFoundException 
     * / 
    @Override 
    protected class <?> the findClass (String name) throws a ClassNotFoundException { 
        // build the absolute path of a class file for I / O read and write operations flow 
        String loadPath convertNameToPath loadRootPath + = (name); 
        // stream among the class file into memory by entering 
        file file = new file (loadPath) ;
        byte [] bytes = readClassFile (File); 
        // arrays into direct Class objects 
        Class = clazz the defineClass (name, bytes, 0, bytes.length) <?>; 
        return clazz; 
    } 

    / ** 
     * The File object class file is read into memory and returns a byte array 
     * @param file 
     * @return 
     * / 
    Private byte [] readClassFile (file file) { 
        // file input stream to build 
        the try (= the FileInputStream new new FIS the FileInputStream (file); 
            ByteArrayOutputStream BAOS = ByteArrayOutputStream new new ()) { 
            int len = 0; 
            byte [] bytes = new new byte [1024]; 
            ! the while ((len = fis.read (bytes, 0, bytes.length)) = -1) { 
                    // read taken directly stored in a cache
                baos.write (bytes, 0, len);  
            }
            // flow directly returns an array of direct 
            return baos.toByteArray (); 
        } the catch (IOException E) { 
            e.printStackTrace (); 
            the throw a RuntimeException new new (E); 
        } 
    } 

    / ** 
     * convert the full class name of a relative path 
     * @return 
     * / 
    Private convertNameToPath String (String name) { 
        String path = name.replace (, the File.separator ".") + ".class"; 
        return path; 
    } 
}

use:

public class Hello{
	public static void main(String[] argo){
		System.out.print("Hello,World");
	}
}

 

{the Main class public 
    public static void main (String [] args) throws Exception { 
   // Test custom class loader 
        DemoClassLoader new new DemoClassLoader DC = ( "F.: / S3 / ClassLoader" + the File.separator); 
        Class clazz = DC. the loadClass ( "the Hello"); 
        Object clazz.newInstance Hello = (); 
        Object of hello2 clazz.newInstance = (); 
        Object target output after the instantiation // 
        System.out.println (Hello); 
        System.out.println (of hello2 ); 
        // the class loader to load the output 
        System.out.println (clazz.getClassLoader ()); 
  } 
}

Output:

// Class object represents the output of 
the Hello @ 677327b6 
// with a loader loads the class file, Class object generator is the same as 
the Hello @ 677327b6 
// will load this class is DemoClassLoader, namely custom loader com.company. DemoClassLoader @ 74a14482

 

Note: If you are a different class loader to load the same class file, then the Class object created is not the same.

 

Guess you like

Origin www.cnblogs.com/zhangcaihua/p/11426092.html