Basics of Java Class Loader


Java class loader is an interesting concept of Java Runtime. We know that in Java,  every executable code is stored  in .java files which are compiled to .class files. These class files are stored in file system  in plain directory structure or in jar files or probably using some other medium. When any java program runs, it needs the definition of referred class files to execute this code at runtime. Here comes the role of Java Class Loader. Whenever Java runtime needs any class file, it calls a component of Java runtime called class loader to load the desired class. Default class loaders of Java i.e. Bootstrap and System Class Loader has the logic to search for the class file in JVM and in  directories and jars included in classpath respectively. It assumes that if Java program is referring to java.lang.Object, then the definition of this class must  be somewhere on  classpath in  java/lang/Object.class hierarchy. So by default, it has the logic to search in directories and jars. Once it finds the class file, it loads it in memory, store it with in memory cache for future reference and return to the runtime. So class loader search for the class files only once, and stores it in memory data structure to be utilized on future calls. Java classes loaded from default class loader are considered as trusted classes and hence these have the access to all core classes of java library itself.

Now Java provide enough flexibility to users applications to define their own custom class loaders, which can extend the default class loaders, and can add custom logic; like to load the classes from a  network location or from database and so on. Working of class loaders generally used to be like; a custom class loader first ask the parent default class loader of Java runtime to load the requested class. If default class loader is unable to find the class, then extended class loader proceed to load that class using its specific loading algorithm.