加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java ClassLoader授权模型?

发布时间:2020-12-14 16:26:18 所属栏目:Java 来源:网络整理
导读:当在 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 r
当在 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,根据包代表委派给类加载器的图),一些类加载器实现将在委派之前在本地类路径中查找类.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读