微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/java/125369.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐