Implementing a custom classLoader

suggest change

Every custom loader must directly or indirectly extend the java.lang.ClassLoader class. The main extension points are the following methods:

The defineClass methods that turn a byte array into a class are final, so they cannot be overridden. Any custom behavior has to happen before the call to defineClass.

Here is a simple loader that defines one class from a byte array. The no-argument ClassLoader constructor sets the parent to the system class loader, so findClass runs only when that parent does not already define the name:

public class ByteArrayClassLoader extends ClassLoader {
    private String classname;
    private byte[] classfile;

    public ByteArrayClassLoader(String classname, byte[] classfile) {
        this.classname = classname;
        this.classfile = classfile.clone();
    }

    @Override
    protected Class findClass(String classname) throws ClassNotFoundException {
        if (classname.equals(this.classname)) {
            return defineClass(classname, classfile, 0, classfile.length);
        } else {
            throw new ClassNotFoundException(classname);
        }
    }
}

Since we have only overridden the findClass method, this custom class loader is going to behave as follows when loadClass is called.

  1. The classloader’s loadClass method calls findLoadedClass to see if a class with this name has already been loaded by this classloader. If that succeeds, the resulting Class object is returned to the requestor.
  2. The loadClass method then delegates to the parent classloader by calling its loadClass call. If the parent can deal with the request, it will return a Class object which is then returned to the requestor.
  3. If the parent class loader cannot load the class, loadClass calls the overridden findClass, passing the name of the class to be loaded.
  4. If the requested name matches this.classname, we call defineClass to load the actual class from the this.classfile byte array. The resulting Class object is then returned.
  5. If the name did not match, we throw ClassNotFoundException.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents