Java Reference
In-Depth Information
}
}
WARNING
Use this with extreme care , because it can defeat some of the most cherished principles of
Java programming.
Loading and Instantiating a Class Dynamically
Problem
You want to load classes dynamically, just like browsers load your applets and web servers
load your servlets.
Solution
Use class.forName("ClassName"); and the class's newInstance( ) method.
Discussion
Suppose you are writing a Java application and want other developers to be able to extend
your application by writing Java classes that run in the context of your application. In other
words, these developers are, in essence, using Java as an extension language, in the same
way that applets are an extension of a web browser. You would probably want to define a
small set of methods that these extension programs would have and that you could call for
such purposes as initialization, operation, and termination. The best way to do this is, of
course, to publish a given, possibly abstract, class that provides those methods and get the
developers to subclass from it. Sound familiar? It should. This is just how web browsers such
as Netscape allow the deployment of applets.
We'll leave the thornier issues of security and of loading a class file over a network socket
for now, and assume that the user can install the classes into the application directory or into
a directory that appears in CLASSPATH at the time the program is run. First, let's define our
class. We'll call it Cooklet (see Example 23-5 ) to avoid infringing on the overused word ap-
Search WWH ::




Custom Search