Java ClassLoader委托模型? [英] Java ClassLoader delegation model?

查看:110
本文介绍了Java ClassLoader委托模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

loadClass()时ClassLoader.htmlrel =noreferrer> ClassLoader ClassLoader 首先检查班级已加载,或是否立即将此检查委托给其父 ClassLoader

When calling loadClass() on a ClassLoader, does the ClassLoader first check if the class has been loaded, or does it immediately delegate this check to its parent ClassLoader?

Java API说:

Java API says:


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

When requested to find a class or resource, a ClassLoader instance will delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself.

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

But there's a specific chapter about class loader in the book Java Reflection in Action that says:


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

Class loader calls findLoadedClass to check if the class has been loaded already.If a class loader does not find a loaded class, calls loadClass on the parent class loader.

Whi ch是正确的吗?

Which is correct?

推荐答案

正确的类加载器实现将:

A proper class loader implementation will:


  1. 检查该类是否已被加载。

  2. 通常要求父类加载器加载类

  3. 尝试在自己的类路径中查找类。

ClassLoader.loadClass的默认实现类似于:

The default implementation of ClassLoader.loadClass is something like:

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

Some class loader implementations will delegation to other non-parent class loaders (OSGi, for example, delegates to a graph of class loaders depending on the package), and some class loader implementations will look for classes in a local classpath before delegating.

这篇关于Java ClassLoader委托模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆