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 java.lang.class.forName("ClassName"); and the class’s newInstance( ) method.

Discussion

Suppose you are using Java as an extension language in a larger application and want customer developers to be able to write Java classes that can run in the context of your application. 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 25-4), to avoid infringing on the overused word applet. And we’ll initially take the easiest path from ingredients to cookies before we complicate it.

Example 25-4. Cooklet.java

/** A simple class, just to provide the list of methods that * users need to provide to be ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.