Video in progress
What is a ClassLoader, and what does it do?
A ClassLoader is the component that finds .class files (on disk, in a jar, over the network) and turns them into Class objects inside the JVM. Each class is identified together with the loader that loaded it.
📖 Answer
The JVM doesn't load all classes at the start. The first time code touches OrderService, this happens:
- Loading: the class file is found and its bytes are read;
- Linking: the bytecode is checked (verification), space is allocated for static fields (preparation), and symbolic references are bound (resolution);
- Initialization: the static blocks and static field values are executed.
The important point: for the JVM, the class name + the ClassLoader that loaded it is the class's full "identity". A com.app.User loaded by two different loaders is two different classes. That is why a strange error sometimes appears: ClassCastException: User cannot be cast to User.
Where you see it: Tomcat gives each web application its own loader, Spring Boot DevTools uses two loaders for reloading, and plugin systems are built on this too.
System.out.println(String.class.getClassLoader()); // null: bootstrap
System.out.println(Main.class.getClassLoader()); // app loader
Sign up to mark studied questions and save your progress.