RMIClassLoader succeeded with Java 1.0 applets but failed with Java 1.1 programs.For his "Java In Depth" column in the October '96 issue of JavaWorld, Chuck McManis discussed in "The basics of Java class loaders." Based on that column, this Java Tip demonstrates how to successfully use the Java 1.1 class loader and goes a lot further.
Let's first examine our requirements for a class loader. We'd like one that:
testing or simulating an Internet server on a client.
The most flexible approach to the above requirements is these three classes:
public abstract class MultiClassLoader extends ClassLoader
public class URLClassLoader extends MultiClassLoader
public class FileClassLoader extends MultiClassLoader
This allows the type of class loader to be determined at runtime and the rest of the application is unaffected.
Hmmmm, fulfilling the above requirements doesn't sound too hard. Let's start with a "Use Case," namely a code example of how
we'll use MultiClassLoader. This is best done by designing our test class, called TestLoader. Now, let's write the TestLoader unit test class. This shows how to set the class loader type at runtime, and then uses it
in a variety of ways to illustrate how to use a class loader effectively. Here is the source code for TestLoader.java.
Let's examine the heart of the test code:
// Init the preferred class loader
MultiClassLoader loader = null;
if (args.length == 0) {
String root = "http://www.mindspring.com/happyjac/";
loader = new URLClassLoader(root);
} else {
loader = new FileClassLoader("store\\");
}
loader.setClassNameReplacementChar('_');
// A series of tests:
Class testClass = null;
try {
testClass = loader.loadClass("Hello");
} catch(Exception ex) {
print("Load failed");
ex.printStackTrace();
return;
}
print("Loaded class " + testClass.getName() );
try {
Runnable hello = (Runnable)testClass.newInstance();
hello.run();
} catch(Exception ex) {
print("Failed to instantiate");
ex.printStackTrace();
}
Good tests are understandable and short. The test first creates an instance of class loader called "loader". Then it uses an optional feature to translate periods to "_".
Next we decide whether to load from the Internet or from a local file, depending on whether any command-line argument was
entered. Note that you will need to set the root or filePrefix to whatever source URL you're using as a base. We have subclassed MultiClassLoader, providing a clean way to provide different specific class sources.