一个合适的类装入器实现将:
- 检查是否已装入类。
- 通常要求父类装入器装入类
- 尝试在类自己的类路径中查找该类。
ClassLoader.loadClass 的默认实现如下所示:
protected synchronized Class<?> loadClass(String name, boolean resolve) {
// First, check if this class loader has directly defined the class or if the
// JVM has initiated the class load with this class loader.
Class<?> result = findLoadedClass(name);
if (result == null) {
try {
// Next, delegate to the parent.
result = getParent().loadClass(name);
} catch (ClassNotFoundException ex) {
// Finally, search locally if the parent could not find the class.
result = findClass(ex);
}
}
// As a remnant of J2SE 1.0.2, link the class if a subclass of the class
// loader class requested it (the JVM never calls the method,
// loadClass(String) passes false, and the protected access modifier prevents
// callers from passing true).
if (resolve) {
resolveClass(result);
}
return result;
}
某些类装入器实现将委派给其他非父类装入器(例如,OSGi 根据包委托给类装入器图),而某些类装入器实现将在委派之前在本地类路径中查找类。