Java ClassLoader委托模型?

Saw*_*yer 12 java classloader

在调用loadClass()a时ClassLoader,是否ClassLoader首先检查是否已加载该类,还是立即将此检查委托给其父级ClassLoader

Java API说:

当请求查找类或资源时,ClassLoader实例会在尝试查找类或资源本身之前,将对类或资源的搜索委托给其父类加载器.

但是在Java Reflection in Action一书中有一个关于类加载器的特定章节,它说:

类加载器调用findLoadedClass来检查是否已经加载了类.如果类加载器没有找到加载的类,则在父类加载器上调用loadClass.

哪个是对的?

Bre*_*ail 17

适当的类加载器实现将:

  1. 检查该类是否已加载.
  2. 通常要求父类加载器加载该类
  3. 尝试在自己的类路径中找到该类.

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,例如,根据包委托给类加载器的图形),并且一些类加载器实现将在委托之前在本地类路径中查找类.

  • 这不是真的。有许多有效的类加载模型,如 http://stackoverflow.com/a/245038/632951 中所述。你所说的“正确”只是其中一种模式。其他模型实际上并不是这样实现的。 (2认同)
  • 你说得对,答案太规范了。我添加了更宽松的语言并添加了类加载器可能偏离的场景示例。感谢您的反馈。 (2认同)