类加载器
JVM通过类加载器ClassLoader,将.class文件中信息拼装成class对象放入内存。
启动类加载器(BootStrapClassLoader)
最顶层类加载器,这个类加载使用C/C++ 语言实现,嵌套在 JVM 内部。主要加载JVAVA_HOME/lib下的rt.jar,resourses.jar,charseters.jar(或 sun.boot.class.path)里面的所有class文件。
BootStrapClassLoader不会继承ClassLoader,没有父类加载器
另外需要注意在jvm启动的时候可以指定-XBootclassPath和路径的改变BootStrap Class Loader的加载目录
扩展类加载器(ExtensionClassLoader)
主要负责加载Java的扩展类库,JVAVA_HOME/lib/ext下的jar和class文件,
系统类加载器(SystemClassLoader)
也称ApplicationClassLoader,主要加载Class Path下面的所有Class文件
自定义类加载器(CustomClassLoader)
类加载器加载的优先级(由高到低):启动类加载器 -> 扩展类加载器 -> 应用程序类加载器 -> 自定义类加载器
类加载器检查的优先级(由低到高):自定义类加载器 -> 应用程序类加载器 ->扩展类加载器 ->启动类加载器
双亲委托是什么
在系统进行类加载,首先会判断当前类是否已被加载,如果被加载了,直接返回类,如果没有加载就会尝试加载,在尝试加载的时候,先要委托双亲加载,双亲请求失败,则会自己加载。
注意:双亲为空的时候有两种情况:一种是当前的双亲就是启动加载器,第二种是本身加载器就是启动加载器
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded
//首先,检查一下class是否已经被加载
Class<?> c = findLoadedClass(name);
if (c == null) {//如果没有被加载过,直接委托给父级类加载
long t0 = System.nanoTime();
try {
//父类不为空,直接让父级类加载
if (parent != null) {
c = parent.loadClass(name, false);
} else {
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found
// from the non-null parent class loader
}
if (c == null) {//如果仍旧没有加载到,只能自己加载
// If still not found, then invoke findClass in order
// to find the class.
long t1 = System.nanoTime();
c = findClass(name);
// this is the defining class loader; record the stats
PerfCounter.getParentDelegationTime().addTime(t1 - t0);
PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
PerfCounter.getFindClasses().increment();
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
双亲委托模型好处
解决了类加载的安全问题,如果父级类已经加载过了,就没有必要再加载了,避免了一些自定义类与核心库类名相同而替换的隐患。在这里还有一点,如果你定义了一个Java.util.List类,父级类已经加载过了,你自定义的这个类就没有办法加载 java: 程序包已存在于另一个模块中: java.base