【深入理解java虚拟机v3】双亲委派模型 代码清单7-9 ClassLoader.getClassLoader()方法的代码片段

原文代码片段

代码清单7-9 ClassLoader.getClassLoader()方法的代码片段

//JDK 1.8
public final class Class<T>  {
    
    
       /**
     * Returns the class loader for the class.  Some implementations may use
     * null to represent the bootstrap class loader. This method will return
     * null in such implementations if this class was loaded by the bootstrap
     * class loader.
     ...
     
     */
    @CallerSensitive
    public ClassLoader getClassLoader() {
    
    
        ClassLoader cl = getClassLoader0();
        if (cl == null)
            return null;
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
    
    
            ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
        }
        return cl;
    }  

该方法的注释明确说明当返回值为null时,表示某个类的加载器使用的是bootstrap class loader。

解析代码片段

java.lang.Class类的getClassLoader()方法用于获取此实体的classLoader,该实体可以是类,数组,接口等。我们知道类加载器类型包括四种,分别是启动类加载器(Bootstrap ClassLoader)、扩展类加载器(Extension ClassLoader)、应用程序类加载器(Application ClassLoader)、用户自定义加载器

我们看个例子:

package my.test;

import sun.misc.Launcher;

public class Test {
    
    

    public static void main(String[] args) {
    
    
        ClassLoader launcherClassLoader = Launcher.class.getClassLoader();
        System.out.println(launcherClassLoader);   //输出null

        ClassLoader testClassLoader = Test.class.getClassLoader();
        System.out.println(testClassLoader); // 输出 sun.misc.Launcher$AppClassLoader@19821f
    }
}

输出:

null
sun.misc.Launcher$AppClassLoader@19821f

sun.misc.Launcher类位于rt.jar包中,由BootstrapClassLoader加载的,而Test 类,由默认加载器,这里是程序类加载器。

猜你喜欢

转载自blog.csdn.net/m0_45406092/article/details/109080458