类加载器ClassLoader

Java168

1.双亲委派模型

java是根据双亲委派模型的加载类的,当一个类加载器加载类时,会先尝试委托给父类加载器去加载,直到到达启动类加载器顶层若加载不了,则再让子类加载器去加载直到类成功加载,否则抛出异常。

双亲委派模型的好处是可以保证类加载的安全性,无论加载哪个类都会向上委托给BootstrapClassLoader类加载器,BootstrapClassLoader加载不了再尝试自己加载,这样就可以保证用不同的类加载器加载可以得到同一个class对象

2. 双亲委派模型的缺陷

根据父类委托模型,子类加载器可以使用父类加载器加载的类,而父类加载器不能使用子类加载器加载的类,因为子类加载器可以向上委托父类加载器。父类加载器不能要求子类加载器向下加载类。因此,父级委托模型并不处理所有类加载方案,并且它有其自身的限制。

[En]

Depending on the parent delegation model, the child class loader can use the class loaded by the parent class loader, while the parent class loader cannot use the class loaded by the child class loader, because the child class loader can delegate the parent class loader upwards. the parent class loader cannot ask the child class loader to load the class down. As a result, the parent delegation model does not handle all class loading scenarios, and it has its own limitations.

此外,类加载器具有命名空间的概念,类加载器的命名空间由这个类加载器加载的类和它的父类加载器加载的类组成,并且不存在相同名称中具有相同完全限定名的两个类对象。同一命名空间的类彼此可见,不同命名空间的类不能相互访问。

[En]

In addition, the class loader has the concept of namespace, the namespace of a class loader consists of the classes loaded by this class loader and the classes loaded by its parent class loader, and there are no two class objects with the same fully qualified name in the same name. classes of the same namespace are visible to each other, and classes of different namespaces cannot access each other.

接下来针对 子类加载器可以使用父类加载器加载的类,而父类加载器无法使用子类加载器加载的类这句话写个简单的例子来证明

3. 用例

首先我们自定义一个类加载器MyClassLoader,它可以加载path路径下的class文件。为了不破坏双亲委派模型,MyClassLoader类没有重写loadClass方法只重写了findClass方法,当父类加载器无法加载指定类的时候,MyClassLoader会调用findClass方法去尝试加载类

以下的类都定义在package包loader下面

输入验证码查看隐藏内容

扫描二维码关注本站微信公众号 Johngo学长
或者在微信里搜索 Johngo学长
回复 svip 获取验证码
wechat Johngo学长

相关文章
Java

20 HTTP 长连接与短连接

纸上得来终觉浅,绝知此事要躬行。 Never give up until the fight is over. 永远不要放弃,要一直战斗到最后一秒。 长连接 指在一个TCP连接上可以连续发送多个数据包...
Java

Java基础常见知识&面试题总结(中)

Java基础常见知识&面试题总结(中) 泛型 Java 泛型了解么?什么是类型擦除?介绍一下常用的通配符? Java 泛型(generics) 是 JDK 5 中引入的一个新特性, 泛型提供了...
Java

Netty源码分析之ByteBuf引用计数

引用计数是一种常用的内存管理机制,是指将资源的被引用次数保存起来,当被引用次数变为零时就将其释放的过程。Netty在4.x版本开始使用引用计数机制进行部分对象的管理,其实现思路并不是特别复杂,它主要涉...
Java

Spider

流程: 迭代进行:种子url->Element遍历获取超链接lin->作为新种子id ⚠️注意频率和遍历深度 1.设定url及请求参数 headers = {"user-agen...
Java

Storm3

```java;gutter:true; package storm.scheduler; import java.lang.management.ManagementFactory; import ...
Java

java 5种IO模型

人的痛苦会把自己折磨到多深呢? You cannot swim for new horizons until you have courage to lose sight of the shore. ...
Java

Java运行过程和跨平台原理

一、Java的运行过程 步骤:编译->运行 将.java源文件进行编译,生成.class字节码文件 java虚拟机对字节码文件进行解释执行 例如:运行HelloWorld.java 编写Hell...
Java

JAVA 线程的6种状态

线程状态(Thread.State)。线程处于下列状态的其中之一。 一个线程一次只能有一个状态。这些状态是虚拟机线程状态,不能反映任何操作系统的线程状态。[En]A thread can only h...