目录
1概述
2类加载时机
虚拟机规范没有规定何时进行加载,但规定了有且只有5种情况立即初始化:
3类加载过程
3.1加载
3.2验证
- 文件格式验证
- 元数据验证
- 字节码验证
- 符号引用验证
3.3准备
3.4解析
3.5初始化
4类加载器
4.1类与类加载器
4.2双亲委派模型
4.2.1类加载器种类
- 从Java虚拟机角度,两种类加载器:
启动类加载器(C++实现),是虚拟机的一部分
其他类加载器,Java语言实现,独立于虚拟机,继承自抽象类java.lang.ClassLoader
- 从Java开发人员角度:
(也叫系统类加载器)
4.2.2双亲委派模型
- 作用:
双亲委派模型保证了Java程序的稳定运行,可以避免类的重复加载(JVM 区分不同类的方式不仅仅根据类名,相同的类文件被不同的类加载器加载产生的是两个不同的类),也保证了 Java 的核心 API 不被篡改。如果不用没有使用双亲委派模型,而是每个类加载器加载自己的话就会出现一些问题,比如我们编写一个称为 java.lang.Object
类的话,那么程序运行的时候,系统就会出现多个不同的 Object
类。
- 实现方式
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded
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
sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
sun.misc.PerfCounter.getFindClasses().increment();
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
4.2.3破坏双亲委派模型
- 第一次:
- 第二次:
加载类D的类加载器Dload,在解析过程中,如果要将D中符号引用N解析为类或者接口C的直接引用,C又未被类加载器加载,那么使用Dload对C进行加载。然而由于JDNI是使用启动类加载器加载的,而JNDI类中符号引用代表的类是第三方的代码,所以无法使用启动类加载器进行加载,所以需要调用应用程序类加载器加载。
- 第三次
有几个注意事项:
Class.forName()采用当前类的类加载器
5模块化下类加载器