Sobes.tech
Junior — Middle

Could you tell me about the types of class loading mechanisms in JVM?

sobes.tech AI

Answer from AI

In JVM, there are several main types of class loaders responsible for loading class bytecode into memory:

  1. Bootstrap ClassLoader — this is a built-in loader implemented in native JVM code. It loads core classes from the JDK, such as from rt.jar (java.lang, java.util, etc.). This loader is not a Java object.

  2. Extension ClassLoader — loads classes from JRE extensions, usually from the lib/ext folder. It is a Java object that extends the functionality of the bootstrap loader.

  3. System (Application) ClassLoader — loads classes from paths specified in the CLASSPATH environment variable or the -classpath parameter. This is the loader that applications typically work with.

Besides these standard loaders, you can create your own class loaders by inheriting from ClassLoader to implement specific loading logic (for example, loading from the network, encrypted files, etc.).

It is important to note that class loaders form a hierarchy and use delegation: if a loader cannot find a class, it delegates the request to its parent loader.

Example of creating a custom loader:

public class MyClassLoader extends ClassLoader {
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // Logic to load the class, for example, from a non-standard source
        byte[] bytes = ...; // load bytecode
        return defineClass(name, bytes, 0, bytes.length);
    }
}