java运行main方法时首先要通过类加载器把类加载到jvm中。
加载步骤:
加载 --》验证--》准备---》解析---》初始化----》使用---》卸载
- 加载:在磁盘上查找字节码文件,在需要使用类时(new 对象时),在内存中创建这个类的class对象,作为方法区这个类的各种数据的访问入口。
- 验证:字节码文件的正确性。
- 准备:给类的静态变量分配内存,并赋默认值。
- 解析:符号引用替换为直接引用,静态链接的过程。
- 初始化:类的静态变量初始化为指定值,执行静态代码块。
类加载器分类:
- 引导类加载器:加载核心类库(jre下的lib目录下的jar包)
- .扩展类加载器:加载jre--->lib-->ext扩展目录下的jar包
- 应用程序类加载器:加载classpath目录下的jar包,自己写的类
- 自定义类加载器:加载用户自定义路径下的类包
双亲委派机制
最先找到应用程序类加载--》使用父类加载器(扩展类加载器)---》未找到使用父类加载器(引到类加载器)--》未找到使用子类加载器(扩展类加载器)--》未找到使用应用程序类加载器--》未找到使用自定义类加载器;
找到要加载的类时结束。
双亲委派机制的作用
- 沙箱安全机制:优先加载核心类库的类,防止核心类库api被篡改,比如自定义的String类是不能覆盖核心类库的。
- 保证类被加载的唯一性:父类加载过得类,就不会再子类再加载一次。
双亲委派机制核心代码:
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;
}
}
自定义类加载器
继承 java.lang.ClassLoader;重写findClass方法;
打破双亲委派机制
重写loadClass方法,
//双亲委派机制,向上查找,加载类信息
if (parent != null) { c = parent.loadClass(name, false); }
else { c = findBootstrapClassOrNull(name); }
删除这段代码 实现自己的类加载方式。
tomcat 中自定义加载器:
1、每发布一个web应用,tomcat都会生成一个对应的自定义加载器,自定义加载器会打破双亲委派机制,只加载当前war包中内容,对于tomcat中共用的jar包,依然使用双亲委派机制去加载。
2、jsp文件修改后tomcat的热加载,每个jsp文件都会有一个对应的自定义类加载器。开启线程监听文件夹中jsp的时间戳,文件有改动的话,卸载jsp文件的类加载器,重新加载jsp文件。