How Classloader determines which classes it can load?

早过忘川 提交于 2019-12-05 02:00:23

问题


I'm reading on class loading in Java.

Motivation

Assuming we have a classloader hierarchy that looks like this, I understand that classes loaded by First are not directly accessible by classes loaded by Second (and vice versa).

 Bootstrap
     |
   System
     |
   Common
   /    \
First Second

I also understand that a classloader checks with its parent class loader whether it can load the class and, if that is the case, delegates the loading to its parent.

Question

How do classloaders actually determine whether they can load some given class?


回答1:


That differs depending on the implementation of the classloader. But all Classes a ClassLoader can load are retrieved by ClassLoader.findClass(String)

There are many implementations but the most common one is the URLClassLoader which loads classes from directories and jar files.




回答2:


The classloader checks all classes (java class files) within your CLASSPATH path variable. If your class is found there, it exists, otherwise it doesn't.

So practically, your /src directory and all subdirectories (=packages) are scanned.




回答3:


The classloader transforms the requested class name into a file name and then tries to find a "class file" of that name from a file system. As @poitroae notes, it uses the CLASSPATH variable, if set, as a starting place. Most IDEs and such extend this to include your working directories for the project.



来源:https://stackoverflow.com/questions/15248405/how-classloader-determines-which-classes-it-can-load

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!