JVM的艺术—类加载器篇(二) (5)

ClassLoader.getSystemClassLoader()方法解读

/** * Returns the system class loader for delegation(该方法返回系统类加载器). This is the default * delegation parent for new ClassLoader instances(也是我们自己定义的类加载器的委托父类), and is * typically the class loader used to start the application(通常系统类加载器是用来启动我们的应用的) * * This method is first invoked early in the runtime's startup * sequence(程序在运行早起就会调用该方法), at which point it creates the system class loader and sets it * as the context class loader of the invoking <tt>Thread</tt>.(在那个时间,调用线程创建我们的系统类加载器同时把系统类加载器设置到我们线程上下文中) * * <p> The default system class loader is an implementation-dependent * instance of this class.(这句话没有很好的理解) * * <p> If the system property "<tt>java.system.class.loader</tt>" is defined * when this method is first invoked then the value of that property is * taken to be the name of a class that will be returned as the system * class loader. The class is loaded using the default system class loader * and must define a public constructor that takes a single parameter of * type <tt>ClassLoader</tt> which is used as the delegation parent. An * instance is then created using this constructor with the default system * class loader as the parameter. The resulting class loader is defined * to be the system class loader. 我们可以通过java.system.class.loader 系统属性来指定一个自定义的类加载的二进制名称作为新的系统类加载器, 在我们自定的加载中我们需要定义个带参数的构造函数,参数为classLoader,那么我们这个自定义的类加载器就会看做系统类加载器 * * @return The system <tt>ClassLoader</tt> for delegation, or * <tt>null</tt> if none * * @throws SecurityException * If a security manager exists and its <tt>checkPermission</tt> * method doesn't allow access to the system class loader. * * @throws IllegalStateException * If invoked recursively during the construction of the class * loader specified by the "<tt>java.system.class.loader</tt>" * property. * * @throws Error * If the system property "<tt>java.system.class.loader</tt>" * is defined but the named class could not be loaded, the * provider class does not define the required constructor, or an * exception is thrown by that constructor when it is invoked. The * underlying cause of the error can be retrieved via the * {@link Throwable#getCause()} method. * * @revised 1.4 */ @CallerSensitive public static ClassLoader getSystemClassLoader() { //初始化系统类加载器 initSystemClassLoader(); if (scl == null) { return null; } SecurityManager sm = System.getSecurityManager(); if (sm != null) { checkClassLoaderPermission(scl, Reflection.getCallerClass()); } return scl; }

1:该方法的作用是返回系统类加载器

2:也是我们自定义加载器的直接父类

3:系统类加载器是用来启动我们的应用的

4:在系统早期,调用线程会创建出我们的系统类加载器,并且把我们的系统类加载器设置到当前线程的上下文中.

5:我们可以通过系统属性:java.system.class.loader来指定一个我们自定义类加载器来充当我们系统类加载器,不过我们的我们自定的加载器需要提供一个带参数(classloader)的构造器

这篇文章就写到这里,jvm的艺术会继续连载,有兴趣的读者可以关注我:

JVM的艺术—类加载器篇(一)已完结

JVM的艺术—类加载器篇(二)已完结

JVM的艺术—类加载器篇(三)创作中

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgyxwp.html