问题描述
我对这两个类加载器非常困惑。在谈到Java类加载器的层次结构时,通常会提到引导类加载器和ext类加载器以及第三个(系统类加载器或应用程序类加载器)。
I am so confused about these two class loaders. When talking about the hierarchy of Java class loaders, usually the bootstrap classloader and ext class loader and the third one (system classloader or app classloader) are mentioned.
为了更准确,我检查了JDK的源代码。在类 Launcher
中,有代码:
To be more accurate, I checked the source code of JDK. In class Launcher
, there is the code:
loader = AppClassLoader.getAppClassLoader(extcl);
在类 ClassLoader
中,方法:
getSystemClassloader()
还说系统类加载器用于启动应用程序。
Also says the system classloader is used to start the application.
那么这是层次结构中的第三个,还是两个类加载器相同?
So which is the third one in the hierarchy, or are the two classloaders the same?
推荐答案
两者 AppClassLoader
和 SystemClassLoader
是一样的。
查看层次结构。
ClassLoader遵循三个原则。
ClassLoader follows three principles.
授权原则
Delegation principle
Bootstrap ClassLoader
负责从rt.jar加载标准JDK类文件,它是Java中所有类加载器的父类。 Bootstrap类加载器没有任何父级。
Bootstrap ClassLoader
is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java. Bootstrap class loader don't have any parents.
扩展ClassLoader
将类加载请求委托给其父级,Bootstrap和如果不成功,则加载类表单jre / lib / ext目录或java.ext.dirs系统属性指向的任何其他目录
Extension ClassLoader
delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property
系统或应用程序类loader
并且它负责从CLASSPATH环境变量,-classpath或-cp命令行选项,JAR中的Manifest文件的Class-Path属性加载特定于应用程序的类。
System or Application class loader
and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.
应用程序类加载器是 Extension ClassLoader
的子代,它由 sun.misc实现.Launcher $ AppClassLoader
class。
Application class loader is a child of Extension ClassLoader
and its implemented by sun.misc.Launcher$AppClassLoader
class.
除了 Bootstrap类加载器
,它是在母语主要在C语言中,所有Java类加载器都是使用 java.lang.ClassLoader
实现的。
Except Bootstrap class loader
, which is implemented in native language mostly in C, all Java class loaders are implemented using java.lang.ClassLoader
.
看看在此,以便更好地了解这些三级装载机。
Have a look at this blog for better understanding of these three class loaders.
可见性原则
Visibility Principle
如果类Abc由应用程序类加载器加载
然后尝试加载类显式使用 Extension ClassLoader
的ABC将抛出 java.lang.ClassNotFoundException
If class Abc is loaded by Application class loader
then trying to load class ABC explicitly using Extension ClassLoader
will throw java.lang.ClassNotFoundException
唯一性原则
Uniqueness Principle
这篇关于AppClassloader和SystemClassloader之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!