Help is available for each task, or you can go straight to
the solution source code.
Task 1
In the
URLTester.java skeleton, create an array holding the URL of the file (directory name) specified from the
command line, as args[0]
.
URL urlList[] = {new File(args[0]).toURL()};
Task 2
Create an instance of URLClassLoader
, using this array in its constructor.
ClassLoader loader = new URLClassLoader(urlList);
Task 3
Next, have the test program load a class whose name will be provided from the command line, also, as args[1]
.
Class c = loader.loadClass (args[1]);
Task 4
After loading the class, create an instance of it. You can use reflection and the Constructor
object, or just the
newInstance
method if the class has a no argument constructor.
Object tester = c.newInstance();
Task 5
The
Tester.java file contains a test class to use for the class loader. The only thing it does is print messages
when the class file is loaded and instances are created. Save and compile the file.
Shift-click on the
Tester.java link to save. Then compile with the following command:
javac Tester.java
Task 6
If you have a ".
" in your CLASSPATH
, move the Tester.class
file to another directory.
Something like the following will do. Depending upon your platform, the specific command may vary.
mkdir test
move Tester.class test
Task 7
Run the URLTester
program. The first argument to the program is the directory you just moved the Tester.class
file to.
The second argument is the class you wish to load, Tester
.
java URLTester test Tester
Task 8
To demonstrate the flexibility of the URLClassLoader
, place the Tester.class
file in a JAR file. Then, tell the
URLTester
program to load the file from the JAR file, instead of a directory.
jar cf test.jar -C test Tester.class
java URLTester test.jar Tester
Copyright © 1998 MageLang Institute.
All Rights Reserved.