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下面