1.关于类加载的loadClass()方法的讲解
loadClass()方法是ClassLoader类中的一个方法
loadClass()方法源码:
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded
/*第一先判断这个类有没有被加载过
如果加载过,返回该类的Class<?>对象
没有加载过返回 null
*/
Class<?> c = findLoadedClass(name);
//如果这个类没有加载过
if (c == null) {
long t0 = System.nanoTime();
try {
//先看父类加载器可不可以加载,parent == null代表着使用根类加载器加载
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();
}
}
//resolve为true进行类加载链接操作,反之不进行
if (resolve) {
resolveClass(c);
}
return c;
}
}