All 15 Class Loading & Bytecode Verification questions
More in Class Loading & Bytecode Verification
Advertisement
Back to results for “Class Loading & Bytecode Verification”
Java › Class Loading & Bytecode Verification

What is the role of the ClassLoader in the JVM, and what are the three built-in bootstrap/platform/application class loaders?

Beginner

Answer

A ClassLoader is responsible for locating and loading .class files (bytecode) into the JVM at runtime, converting them into Class objects usable by running code -- the JVM has a hierarchy of built-in loaders: the Bootstrap ClassLoader (written in native code, loads core JDK classes like java.lang.* from the JDK's own modules), the Platform ClassLoader (loads other JDK platform classes), and the Application/System ClassLoader (loads classes from the application's own classpath, the one typically used for your own application code).
public class Main {
    public static void main(String[] args) {
        ClassLoader loader = Main.class.getClassLoader();
        System.out.println(loader);  // typically: jdk.internal.loader.ClassLoaders$AppClassLoader

        ClassLoader stringLoader = String.class.getClassLoader();
        System.out.println(stringLoader);  // null, since String is loaded by the Bootstrap loader
    }
}
Real-world example A diagnostic logging statement printing which ClassLoader loaded a given class helps a team investigating a mysterious ClassCastException discover that two different ClassLoaders had independently loaded the same class name from different JARs, which the JVM treats as genuinely different types despite an identical class name.

Common follow-ups: Why does String.class.getClassLoader() return null instead of an actual ClassLoader instance?;What determines which of the three built-in class loaders is responsible for loading a particular class?