类加载的过程其中一个核心点就是sun.misc.Launcher类会初始化三个类加载器
1、引导类加载器由c++实现:主要负责加载jdk的jre中lib下的rt.jar或者其它的依赖包。
2、扩展类加载器exeClassLoader:主要负责加载jre中lib/ext目录下的jar包
3、应用类加载器appClassLoader:主要加载自己编写的类包
–双亲委派
?为啥要用双亲委派来实现类加载。
?为啥双亲委派机制从appClassLoader开始。
?能否打破双亲委派,如何打破。
先看个流程图
由图可以查看,类加载是一个委托的过程,首先看父类中是否已经加载过,倘若最终父类没有加载过那么就让子类自己加载。
核心代码实现如下:
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); // 判断当前this中是否已经加载
if (c == null) {
long t0 = System.nanoTime();
try {
if (parent != null) {
c = parent.loadClass(name, false); // 存在父类则递归调用父类加载
} else {
c = findBootstrapClassOrNull(name); // 最终类检查是否此类已被加载过,没有返回Null
}
} 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;
}
}
以上就是双亲委派的过程,接下来谈谈上面遗留问题的理解吧!
–双亲委派使用是为了1、沙盒安全,防止核心api类被篡改。2、避免类的重复加载。
–每次频繁访问的都是我们的应用级别的类,避免每次都从最终父类的流程走下来。
–当然可以打破,重写loadClass()这个方法就可以
倘若我们想要自定义加载类可以通过继承ClassLoader重写findClass(),但是加载自定义类的加载器依旧是APP…因为还是遵循的双亲委派机制。想要拿到的加载器是自定义的那么我们还需要重写loadClass()来打破双亲委派机制。这里需要注意几个点。
一些类如string,object是系统基本类,是引导类加载的。如果我们自定义类中有这些类,但是我们现在打破了双亲委派机制,需要做判断处理一下。区分自定义加载类不适用双亲委派,其它的仍然走双亲委派。