Class ClassLoader

Class java.lang.ClassLoader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.ClassLoader

public abstract class ClassLoader
extends Object

The class ClassLoader is an abstract class. Applications implement subclasses of ClassLoader in order to extend the manner in which the Java Virtual Machine dynamically loads classes.

Normally, the Java Virtual Machine loads classes from the local file system in a platform-dependent manner. For example, on UNIX systems, the Virtual Machine loads classes from the directory defined by the CLASSPATH environment variable.

However, some classes may not originate from a file; they may originate from other sources, such as the network, or they could be constructed by an application. The method defineClass converts an array of bytes into an instance of class Class. Instances of this newly defined class can be created using the newInstance method in class Class.

The methods and constructors of objects created by a class loader may reference other classes. To determine the class(es) referred to, the Java Virtual Machine calls the loadClass method of the class loader that originally created the class. If the Java Virtual Machine only needs to determine if the class exists and if it does exist to know its superclass, the resolve flag is set to false. However, if an instance of the class is being created or any of its methods are being called, the class must also be resolved. In this case the resolve flag is set to true, and the resolveClass method should be called.

For example, an application could create a network class loader to download class files from a server. Sample code might look like:

The network class loader subclass must define the method loadClass to load a class from the network. Once it has downloaded the bytes that make up the class, it should use the method defineClass to create a class instance. A sample implementation is:


     class NetworkClassLoader {
         String host;
         int port;
         Hashtable cache = new Hashtable();
         private byte loadClassData(String name)[] {
         // load the class data from the connection
          . . .
         }
         public synchronized Class loadClass(String name,
                                             boolean resolve) {
             Class c = cache.get(name);
             if (c == null) {
                 byte data[] = loadClassData(name);
                 c = defineClass(data, 0, data.length);
                 cache.put(name, c);
             }
             if (resolve)
                 resolveClass(c);
             return c;
         }
     }
 

See Also:
Class, newInstance, defineClass, loadClass, resolveClass