4

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?

ipavlic
  • 4,906
  • 10
  • 40
  • 77

3 Answers3

5

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.

Blank Chisui
  • 1,043
  • 10
  • 25
0

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.

poitroae
  • 21,129
  • 10
  • 63
  • 81
0

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.

WPrecht
  • 1,340
  • 1
  • 17
  • 29