Implementing a custom classLoader
suggest changeEvery custom loader must directly or indirectly extend the java.lang.ClassLoader class. The main extension points are the following methods:
findClass(String)— override this method if your class loader follows the standard delegation model.loadClass(String, boolean)— override this method to implement an alternative delegation model.findResourceandfindResources— override these methods to customize resource loading.
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.
- The classloader’s
loadClassmethod callsfindLoadedClassto see if a class with this name has already been loaded by this classloader. If that succeeds, the resultingClassobject is returned to the requestor. - The
loadClassmethod then delegates to the parent classloader by calling itsloadClasscall. If the parent can deal with the request, it will return aClassobject which is then returned to the requestor. - If the parent class loader cannot load the class,
loadClasscalls the overriddenfindClass, passing the name of the class to be loaded. - If the requested name matches
this.classname, we calldefineClassto load the actual class from thethis.classfilebyte array. The resultingClassobject is then returned. - If the name did not match, we throw
ClassNotFoundException.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents