Java ClassLoader授权模型?

当在 ClassLoader调用loadClass()时,ClassLoader是否首先检查该类是否被加载,或者立即将此检查委托给其父级ClassLoader?

Java API说:

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反思行动书中有一个关于类加载器的具体章节:

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.

哪个是对的?

解决方法

正确的类加载器实现将:

>检查课程是否已经加载.
>通常要求父类加载器加载类
>尝试在自己的类路径中找到该类.

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...