简体   繁体   English

在Java中动态加载类时

[英]When dynamically loading a class in java

Suppose in java I'm dynamically loading class A . 假设在Java中我正在动态加载类A
Class A uses both java standard library classes and A同时使用Java标准库类和
user defined classes. 用户定义的类。
I'm wondering what is the classloader that has to load all of the classes used by A ? 我想知道必须加载A使用的所有类的类加载器是什么?

thanks 谢谢

It depends on the the way you have designed the classloader that loaded the class A 这取决于您设计加载类A的类加载器的方式

First of all, the classloaders will have a hierarchical relation among them. 首先,类加载器之间将具有层次关系。

Standard Java mechanism (Parent first): 标准Java机制(家长优先):

Usually when you have to load a class, by default, it follows this pattern: 通常,当您必须加载类时,默认情况下,它遵循以下模式:

  1. Check if the parent classloader can load the class (each class loader will delegate to its parent) 检查父类加载器是否可以加载该类(每个类加载器将委托给其父类)
  2. If the parent cannot load the class, then the child class loader attempts to load it. 如果父类无法加载该类,则子类加载器将尝试加载它。
  3. If the child is also not able to load it, then a ClassNotFoundException is raised. 如果子项也无法加载,则引发ClassNotFoundException。

Special Case (Child First): 特殊情况(儿童优先):

In this scenario, the child class loader (that is your class loader can attempt to load the class), if this class loader cannot load the required class, then it can ask the parent to load the class. 在这种情况下,子类加载器(即您的类加载器可以尝试加载该类),如果该类加载器无法加载所需的类,则可以要求父类加载器。 If the parent cannot load the class, then a ClassNotFoundException is raised 如果父级无法加载该类,则引发ClassNotFoundException


In any scenario, the java core classes should be loaded by the parent class loader. 在任何情况下,java核心类都应由父类加载器加载。
However in theory, you can always make your custom classloader to load those classes as long as you have access to the jar containing those classes 但是从理论上讲,只要可以访问包含这些类的jar,就可以始终使自定义类加载器加载这些类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM