层次结构和类图
ClassLoader层次结构:
UML类图:
- sun.misc.Launcher.ExtClassLoader
- sun.misc.Launcher.AppClassLoader
显式加载类
在代码中显式加载某个类,有三种方法:
- this.getClass().getClassLoader().loadClass()
- Class.forName()
- MyClassLoader.findClass()
ClassLoader.loadClass()
ClassLoader.loadClass()的加载步骤为:
- 调用
findLoadedClass(String)
来检查是否已经加载类。 - 在父类加载器上调用
loadClass
方法。如果父类加载器为 null,则使用虚拟机的内置类加载器。 - 调用
findClass(String)
方法查找类。
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
/**
* Loads the class with the specified <a href="#name">binary name</a>. The
* default implementation of this method searches for classes in the
* following order:
*
* <p><ol>
*
* <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
* has already been loaded. </p></li>
*
* <li><p> Invoke the {@link #loadClass(String) <tt>loadClass</tt>} method
* on the parent class loader. If the parent is <tt>null</tt> the class
* loader built-in to the virtual machine is used, instead. </p></li>
*
* <li><p> Invoke the {@link #findClass(String)} method to find the
* class. </p></li>
*
* </ol>
*
* <p>
*/
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
// First, check if the class has already been loaded
Class c = findLoadedClass(name);