How to write a custom class loader in java?

In this post we will give you a simple example of custom class loader. We will also touch upon out of the box class loaders in java and the chaining concept.

Java Class Loaders

  1. Bootstrap Class Loader
  2. Extensions Class Loader
  3. System Class Loader
  4. Custom class loader or User Defined Class Loader

Class loader responsibility

Name Class loader class Responsible to load Level
Bootstrap Written in native language JAVA_HOME/lib 1
Extension sun.misc.Launcher$ExtClassLoader JAVA_HOME/lib/ext 2
System sun.misc.Launcher$AppClassLoader Classpath 3
Custom Your Class Custom Location 4

Except the bootstrap class loader every other class loader is written in java. Every class loader except the bootstrap has a parent class loader. When a class loader is asked to load a class, it request it’s parent to load the class. Only if the parent is not able to find the class then the class loader itself will try to find the class. This process is called chaining.

Steps to write a custom class loader

  1. Extend java.lang.ClassLoader.
  2. Override public Class<?> loadClass(final String name) method.
  3. Load class file as or resource stream.
  4. Convert the file stream to byte array.
  5. Call Class<?> defineClass(String name, byte[] b, int off, int len) method in the java.lang.ClassLoader class.
  6. Call void resolveClass(Class<?> c) in the java.lang.ClassLoader class.

Custom Class Loader Code Snippet

Class Loader Static Design

Class Loader static design

Complete Sample Code