What is the purpose of class loaders?

In Java, classes are loaded dynamically. It is done by class loaders, which are descendants of the abstract class ClassLoader. These loaders are also responsible for loading resource files.

The loading of a class (actually of any reference type) and all its ancestors occurs automatically before its initialization. For that the loader that loaded the current code is used, making the loading of all classes, even built-in ones, lazy.

A class can be manually loaded from a specific loader by passing the binary name of the class as an argument to the loadClass mehtod.

In URLClassLoader and standard JVM loaders, the source of the class is a .class file. Other loaders in their implementations use different sources: this could be a network resource, or a class could be generated at runtime. For example, a loader from javassist specializes in creating classes on the fly.

As a result of loading, an instance of the Class class is created. Unlike regular objects, such instances are not stored in the heap but in permgen/metaspace. A Class might be unloaded when the ClassLoader that loaded it becomes eligible for garbage collection.