FAQ: What is a ClassLoader in Java?
FAQ
Approx read time: 2.3 min.
What is a ClassLoader in Java?
A classloader in Java is a subsystem of Java Virtual Machine, dedicated to loading class files when a program is executed; ClassLoader is the first to load the executable file.
Java has Bootstrap, Extension, and Application classloaders.
A `ClassLoader` in Java is a fundamental part of the Java Runtime Environment (JRE) that is responsible for dynamically loading Java classes into the Java Virtual Machine (JVM) during runtime. The primary functions of a ClassLoader include:
1. Loading Classes: The ClassLoader loads classes from various sources like file systems, network sources, or archives (like JAR or ZIP files). It converts the binary data (bytecode) of these classes into `Class` objects.
2. Linking: After loading a class, the ClassLoader performs the linking process. Linking involves verification (checking the correctness of the bytecode), preparation (allocating memory for class variables and initializing them), and optionally, resolution (transforming symbolic references in the class to direct references).
3. Initialization: This involves executing the static blocks of a class and initializing static variables. Initialization is done in the context of the ClassLoader that loaded the class.
Java uses a hierarchical approach for class loading:
– Bootstrap ClassLoader: This is the parent of all class loaders and loads the core Java APIs located in the `<JAVA_HOME>/jre/lib` directory. It is written in native code, not Java.
– Extension ClassLoader: This loads classes from the extensions directories (`<JAVA_HOME>/jre/lib/ext` or any other directory specified by the `java.ext.dirs` system property).
– System/Application ClassLoader: This is responsible for loading classes from the system classpath. It’s the class loader that typically loads the classes of your application.
– Custom ClassLoaders: Java allows you to create your own class loaders by extending the `ClassLoader` class. This is particularly useful for applications like web servers or IDEs that need to load classes in a flexible and isolated manner, such as loading classes from a specific directory or over the network, or for implementing hot deployment of new versions of classes.
The ClassLoader plays a crucial role in Java’s security model and also in its dynamic, modular architecture. It allows Java applications to load classes that may not be present at compile time and supports the Java runtime environment’s core concept of “write once, run anywhere” (WORA).
Related Posts:
Why is Java a platform independent language?(Opens in a new browser tab)
What is Java technology and why do I need it?(Opens in a new browser tab)
Learn about programming Classes and Objects in Python(Opens in a new browser tab)
What are the differences between C++ and Java?(Opens in a new browser tab)
2019 Fall Programs at GTA Photography Classes(Opens in a new browser tab)