classes will typically return null, indicating it was loaded by the bootstrap loader.
You can get the parent class loader from the method getParent. If the class loader's parent is the bootstrap
class loader, getParent may return null.
Class loaders are an integral part of the security architecturesee "Security" on page 677so creating a class
loader and asking for the parent class loader are checked operations that may throw a
SecurityException.
The primary method of ClassLoader is loadClass:
public Class<?>loadClass(String name)tHRows
ClassNotFoundException
Returns the Class object for the class with the specified binary name,
loading the class if necessary. If the class cannot be loaded you will get a
ClassNotFoundException.
The default implementation of loadClass, which is not usually overridden, attempts to load a class as
follows:
It checks to see if the class has already been loaded by invoking findLoadedClass.
ClassLoader maintains a table of Class objects for all the classes loaded by the current class
loader. If a class has been previously loaded findLoadedClass will return the existing Class
object.
1.
If the class has not been loaded it invokes loadClass on the parent class loader. If the current class
loader does not have a parent, the bootstrap class loader is used.
2.
- If the class still has not been loaded, findClass is invoked to locate and load the class.
Note that the parent class loader is always given the chance to load the class first; only if the bootstrap loader
and the system class loader fail to load a given class will your custom class loader be given the opportunity to
do so. The implication is that your custom class loader must search for classes in places that are different from
those searched by the system or bootstrap class loaders.
The PlayerLoader class extends ClassLoader to override findClass:
class PlayerLoader extends ClassLoader {
public Class<?> findClass(String name)
throws ClassNotFoundException
{
try {
byte[] buf = bytesForClass(name);
return defineClass(name, buf, 0, buf.length);
} catch (IOException e) {
throw new ClassNotFoundException(e.toString());
}
}
// ... bytesForClass, and any other methods ...
}
The findClass method generally has to perform two actions. First, it has to locate the bytecodes for the
specified class and load them into a byte arraythe job of bytesForClass in our example. Second, it uses
the utility method defineClass to actually load the class defined by those bytes into the virtual machine
and return a Class object for that class.