What is ClassLoader in Java?
sobes.tech AI
Answer from AI
ClassLoader in Java is an abstract class (java.lang.ClassLoader) responsible for loading classes during program execution. It finds the class bytecode (.class file), converts it into a Class object, and stores it in JVM memory.
Main functions of ClassLoader:
- Loading: Reading class bytecode from various sources (file, network, etc.).
- Verification: Performing security checks on the loaded bytecode.
- Linking:
- Verification: Checking the correctness of bytecode.
- Preparation: Initializing static variables of the class with default values.
- Resolution: Loading classes referenced by the current class, if necessary (dynamically).
- Initialization: Executing static blocks and assigning static variables.
ClassLoader hierarchy:
Java has a hierarchy of ClassLoaders with delegation:
- Bootstrap ClassLoader: Loads core JDK classes (
rt.jar). Written in C++ and part of JVM. - Extension ClassLoader: Loads classes from the
jre/lib/extdirectory. It is a child of the Bootstrap ClassLoader. - System (Application) ClassLoader: Loads classes from the application directory (
classpath). It is a child of the Extension ClassLoader. Returned by the methodClassLoader.getSystemClassLoader().
When loading a class, the ClassLoader first delegates the request to its parent. If the parent cannot find or load the class, the current ClassLoader attempts to find it itself. This prevents loading the same class multiple times and ensures consistency.
Example of obtaining a ClassLoader:
// Getting the System ClassLoader
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
// Getting the ClassLoader of the Object class
ClassLoader objectClassLoader = Object.class.getClassLoader();
Custom ClassLoader:
You can create your own ClassLoaders by extending ClassLoader to load classes from non-standard sources or apply special loading logic.
// Example of a simple Custom ClassLoader (for demonstration)
class CustomClassLoader extends ClassLoader {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// In a real scenario, here would be the logic to read bytecode
throw new ClassNotFoundException(name);
}
}
ClassLoaders are important for modularity, security, and dynamic code loading in Java.