在调用loadClass()a时ClassLoader,是否ClassLoader首先检查是否已加载该类,还是立即将此检查委托给其父级ClassLoader?
Java API说:
当请求查找类或资源时,ClassLoader实例会在尝试查找类或资源本身之前,将对类或资源的搜索委托给其父类加载器.
但是在Java Reflection in Action一书中有一个关于类加载器的特定章节,它说:
类加载器调用findLoadedClass来检查是否已经加载了类.如果类加载器没有找到加载的类,则在父类加载器上调用loadClass.
哪个是对的?
Bre*_*ail 17
适当的类加载器实现将:
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;
}
Run Code Online (Sandbox Code Playgroud)
一些类加载器实现将委托给其他非父类加载器(OSGi,例如,根据包委托给类加载器的图形),并且一些类加载器实现将在委托之前在本地类路径中查找类.
| 归档时间: |
|
| 查看次数: |
9178 次 |
| 最近记录: |