Classloader in short
Classloader is an abstract class which is responsible for loading classes at runtime. There are 3 known loaders. You can also implement custom loaders to do dynamic loading from anywhere like from network, database, etc.
3 loaders are list below, each is the parent of the lower one.
- Bootstrap Classloader. It loads classes from JDK under JRE lib folder.
- Extension Classloader. It loads classes lies in JRE ext folder.
- App Classloader(aka System Classloader). It loads classes defined in current classpath.
Classloader uses a delegation model. Each Classloader loads a class by delegation to its parent. If the parent cannot load the class, it will load it itself.
object Test {
class Util
def main(args: Array[String]): Unit = {
println(ClassLoader.getSystemClassLoader) // AppClassloader
println(classOf[Util].getClassLoader) // AppClassloader
println(classOf[String].getClassLoader) // null
}
}
Let’s look over the above code.
- System classloader is just App classloader, so the first line prints out App loader.
- Util is a new class which lies in classpath, so it should be loaded by App loader.
- The first two lines returns the same App loader.
- String is a type defined in JDK. So it’s loaded by Bootstrap Classloader. And Bootstrap which is implemented by cpp in JVM bootstraps the whole Java app . There’s no corresponding Java class, so it returns null.