雙親委派的源碼在ClassLoader 的 loadClass() 方法中,其實(shí)現(xiàn)原理如下:
- 1.檢查目標(biāo)class是否曾經(jīng)加載過(guò),如果加載過(guò)則直接返回;
- 2.如果沒(méi)加載過(guò),把加載請(qǐng)求傳遞給 parent 加載器去加載;
- 3.如果 parent 加載器加載成功,則直接返回;
- 4.如果 parent 未加載到,則自身調(diào)用 findClass() 方法進(jìn)行尋找,并把尋找結(jié)果返回。
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;
}
}