Classic Tutorials for Java Beginners

The basics of Java class loaders

The fundamentals of this key component of the Java architecture

1 2 Page 2
Page 2 of 2

This interface is shared between my local class repository (it is in the classpath of my application) and the loaded module. A test class helps illustrate the class loader in operation. The code below shows an example class named TestClass that implements the shared interface. When this class is loaded by the SimpleClassLoader class, we can cast instantiated objects to the common interface named LocalModule.

 
import java.util.Random; 
import java.util.Vector>; 
public class TestClass implements LocalModule { 
    /* 
     * This is an example of a class reference that will be resolved 
     * at load time. 
     */ 
    Vector v = new Vector(); 
    /** This is our start function */ 
    public void start(String opt) { 
        /* This reference will be resolved at run time. */ 
        Random r; 
        System.out.println("Running the Test class, option was                   '"+opt+"'"); 
        System.out.println("Now initializing a Random object."); 
        r = new Random(); 
        for (int i = 0; i < 5; i++) { 
            v.addElement(new Integer(r.nextInt())); 
        } 
        /* This reference should get the cached copy of random. */ 
        r = new Random(); 
        System.out.println("A series of 5 random numbers: "); 
        for (int i = 0; i < v.size(); i++) { 
            Integer z = (Integer)v.elementAt(i); 
            System.out.println(i+": "+z); 
        } 
    } 
} 

This test class is to be loaded by our simple class loader and then executed by the example application. There are a couple of interesting things to try and do when running the application. First, watch which classes get loaded and when they get loaded. The initialization of v and the static reference to System cause these classes to be loaded. Furthermore, since out is actually a PrintStream object, this class gets loaded as well, and perhaps suprisingly the class java.lang.StringBuffer gets loaded. This last class is loaded because the compiler automatically changes string expressions into invocations of StringBuffer objects.

When you run it, you will notice that the java.util.Random class is not loaded until after the statement "Now initializing a Random object" is printed. Even though it was referenced in the definition of r, it is not actually used until the new operator is executed. The last thing to notice is that the second time java.util.Random is referenced, your class loader does not get a chance to load it; it is already installed in the virtual machine's loaded class database. It is this latter feature that will be changed in a future release of Java to support garbage collectible classes.

Our simple application Example ties everything together:

 
public class Example { 
    public static void main(String args[]) { 
        SimpleClassLoader sc = new SimpleClassLoader(); 
        Object o; 
        String tst = "TestClass"; 
        System.out.println("This program will use SimpleClassLoader."); 
             if (args.length != 0) 
                 tst = args[0]; 
             try { 
                 o = (sc.loadClass(tst)).newInstance(); 
                ((LocalModule) o).start("none"); 
             } catch (Exception e) { 
                 System.out.println("Caught exception : "+e); 
             } 
        } 
} 

This simple application first creates a new instance of SimpleClassLoader and then uses it to load the class named TestClass (which is shown above). When the class is loaded, the newInstance() method (defined in class Class) is invoked to generate a new instance of the TestClass object; of course, we don't know it's a TestClass. However, our application has been designed to accept only classes that implement the LocalModule interface as valid loadable classes. If the class loaded did not implement the LocalModule interface, the cast in line #12 will throw a ClassCastException. If the cast does succeed then we invoke the expected start() method and pass it an option string of "none."

Winding down, wrapping up

With this introduction you should have enough information to build an application with its own custom class loader. Feel free to base any code you wish on the code in this article (for commercial or non-commercial purposes).

Class loaders provide the mechanism that allows Java applications, whether they are Web browsers or EMACs replacements, to be dynamically extended in a controlled way with additional Java code. The applications of class loaders are bounded only by your imagination. Some interesting experiments for you to run if you download and compile the code.

  • Try creating two instances of SimpleClassLoader and see what programs loaded by separate class loaders can, and cannot, do to or with each other.
  • Think of how you might be able to implement class identity checks with a class loader.
  • Try writing a text editor where every key is bound to a dynamically loaded Java class, then send me a copy. :-)

Next month I think I'll focus a bit on application development in Java, building something a bit more significant than spinning pictures or tumbling mascots.

Chuck McManis is currently the director of system software at FreeGate Corp. FreeGate is a venture-funded start-up that is exploring opportunities in the Internet marketplace. Before joining FreeGate, McManis was a member of the Java group. He joined the Java group just after the formation of FirstPerson Inc. and was a member of the portable OS group (the group responsible for the OS portion of Java). Later, when FirstPerson was dissolved, he stayed with the group through the development of the alpha and beta versions of the Java platform. He created the first "all Java" home page on the Internet when he did the programming for the Java version of the Sun home page in May 1995. He also developed a cryptographic library for Java and versions of the Java class loader that could screen classes based on digital signatures. Before joining FirstPerson, Chuck worked in the operating systems area of SunSoft developing networking applications, where he did the initial design of NIS+.

Learn more about this topic

1 2 Page 2
Page 2 of 2