Java Reference
In-Depth Information
Constructing a Class from Scratch with a ClassLoader
Problem
You need to load a class from a nonstandard location and run its methods.
Solution
Examine the existing loaders such as java.net.URLClassLoader . If none is suitable, write
and use your own ClassLoader .
Discussion
A ClassLoader , of course, is a program that loads classes. One class loader is built into the
Java Virtual Machine, but your application can create others as needed. Learning to write and
run a working class loader and using it to load a class and run its methods is a nontrivial ex-
ercise. In fact, you rarely need to write a class loader, but knowing how is helpful in under-
standing how the JVM finds classes, creates objects, and calls methods.
ClassLoader itself is abstract; you must subclass it, presumably providing a loadClass()
method that loads classes as you wish. It can load the bytes from a network connection, a
local disk, RAM, a serial port, or anywhere else. Or you can construct the class file in
memory yourself, if you have access to a compiler.
There is a general-purpose loader called java.net.URLClassLoader that can be used if all
you need is to load classes via the Web protocol (or, more generally, from one or more
URLs).
You must call the class loader's loadClass() method for any classes you wish to explicitly
load from it. Note that this method is called to load all classes required for classes you load
(superclasses that aren't already loaded, for example). However, the JVM still loads classes
that you instantiate with the new operator “normally” via CLASSPATH.
When writing a class loader, your loadClass() method needs to get the class file into a byte
array (typically by reading it), convert the array into a Class object, and return the result.
What? That sounds a bit like “And Then a Miracle Occurs…” And it is. The miracle of class
creation, however, happens down inside the JVM, where you don't have access to it. Instead,
your ClassLoader has to call the protected defineClass() method in your superclass
Search WWH ::




Custom Search