This magercise takes you through the steps to create a custom class loader. The class loader you are about to create works like the default
class loader, but instead of working with the CLASSPATH
environment variable, you tell the class loader a specific directory to load
class files from. The class loader will load any support files from the CLASSPATH
, as classes like Object
must come
from trusted locations.
Working from the
FileClassLoader.java skeleton, have FileClassLoader
subclass
ClassLoader
.
Find out if the requested class to loadClass
is already loaded. Remember to check for system classes, too.
If the class isn't loaded, you'll need to convert the class name to a file name and load the data from the class. The filename conversion
is already done for you and the loading of the data is already done. The only thing you need to do is connect everything. Just call the
private loadClassData
method with the filename for the class. The method returns the data from the file in a byte array, so you'll
need to save this.
Once you have the class data in a byte array, convert the byte array into a Class
. In the event the byte data is invalid, throw an
exception.
Resolve the class definition if appropriate.
Return the class object just created.
In the
CLTester.java skeleton, create an instance of the FileClassLoader
. Have the directory name
that you use to load files from, come from the command line, as args[0]
.
Next, have the test program load a class whose name will be provided from the command line, also, as args[1]
. The public version
of loadClass()
doesn't have a resolve argument, and defaults to true.
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.
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.
If you have a ".
" in your CLASSPATH
, move the Tester.class
file to another directory.
Run the CLTester
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 want to load Tester
.