8, the class loader case analysis

8.1, using class ClassLoader getParent () method to get the parent class loader

package com.shtec.classLoader;

/**
 * Use class ClassLoader getParent () method to get the parent class loader
 * Note: The root class loader is written in C ++, an object which is null;
 * @Author Sunhao
 *
 */
public class Test04 {
    
    public  static  void main (String [] args) {
         // get the system class loader] [ 
        ClassLoader classLoader = ClassLoader.getSystemClassLoader ();
        System.out.println ( "class loader system:" + classLoader);
         // sequentially acquired extension class loader [], [] Root class loader 
        the while (classLoader =! Null ) {
            classLoader = classLoader.getParent();
            System.out.println(classLoader);
        }
        // output: 
        / *
         * System class loader: sun.misc.Launcher$AppClassLoader@73d16e93
         * sun.misc.Launcher$ExtClassLoader@15db9742
         * null
         */
    }
}

8.2, in accordance with the resource information acquired path bytecode

package com.shtec.classLoader;

import java.io.IOException;
import java.net.URL;

/**
 * Get the path resource information bytecode
 * @Author Sunhao
 *
 */
public class Test05 {

    public static void main(String[] args) throws IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String resourceName = "com/shtec/classLoader/Test05.class";
        URL url = classLoader.getResource(resourceName);
        System.out.println(url);
        // Output:
         // File: / D: /workspace_m/jvm/target/classes/com/shtec/classLoader/Test05.class 
    }
}

8.3, obtain a class loader to load classes and general class String

package com.shtec.classLoader;

/**
 * Get the class loader loads common classes and the String class
 * @Author Sunhao
 *
 */
public class Test06 {
    
    public  static  void main (String [] args) throws Exception {
         // load the class loader normal class -----> the AppClassLoader 
        Class <> = clazz Test06?. class ;
        System.out.println(clazz.getClassLoader());
        
        // Load String class class loader -----> root class loader 
        clazz = the Class.forName ( "java.lang.String" );
        System.out.println(clazz.getClassLoader());
        
        // output: 
        / *
         * sun.misc.Launcher$AppClassLoader@73d16e93
         * null
         * 
         */
    }
}

Guess you like

Origin www.cnblogs.com/sunhao1234/p/12339980.html