简体   繁体   English

不同的类加载器如何解析引用

[英]How different classloaders resolve reference

If i create a custom class loader for say 3(A,B,C) classes of my Java app and redirect all other loading to default bootstrap class loader. 如果我为我的Java应用程序的3(A,B,C)类创建一个自定义类加载器,并将所有其他加载重定向到默认的bootstrap类加载器。 Then according to JVM spec : "A reference to a class is consulted from current class loader and loaded (if necessary ) accordingly" 然后根据JVM规范:“从当前类加载器查询类的引用并相应地加载(如果需要)”

Now if i try to create object of class D(whose Class-Loader reference is bootstrap in "Class" class) from class A(whose Class-Loader reference is custom loader) , then custom-loader does not have any way to find path of D.class file (say i pick A,B,C from internet / some other place in which case , CLASSPATH is different in custom loader). 现在,如果我尝试从类A(其类加载器引用是自定义加载器)创建类D的对象(其类加载器引用是“类”类中的引导),则自定义加载器无法找到路径D.class文件(比如我从互联网/其他地方选择A,B,C),在这种情况下,CLASSPATH在自定义加载程序中是不同的。

So how does this class finding problem would be resolved by JVM? 那么如何通过JVM解决这个类发现问题呢?

If you implement your custom classloader correctly there will be no problem. 如果正确实现自定义类加载器,则没有问题。 All classloaders have a parent. 所有类加载器都有父级。 For a custom classloader it's typically the system class loader, the one that loads classes from Java class path. 对于自定义类加载器,它通常是系统类加载器,即从Java类路径加载类的加载器。 Typically classloader first of all offers (delegates) its parent to load a class and only if the parent fails then it tries to load the class. 通常,类加载器首先提供(委托)其父级来加载类,并且只有当父级失败时它才会尝试加载该类。 To make this happen custom classloader needs to implement findClass method and the delegation will be done automatically by ClassLoader.loadClass. 为了实现这一点,自定义类加载器需要实现findClass方法,并且委托将由ClassLoader.loadClass自动完成。

Note that JVM has not only bootstrap class loader but a hierarchy of three class loaders 请注意,JVM不仅具有引导类加载器,还具有三个类加载器的层次结构

bootstrap <- extension <- system bootstrap < - extension < - system

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

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