Java ClassLoader授权模型?

前端之家收集整理的这篇文章主要介绍了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,根据包代表委派给类加载器的图),一些类加载器实现将在委派之前在本地类路径中查找类.

原文链接:https://www.f2er.com/java/125369.html

猜你在找的Java相关文章