Let's create a simple installed extension. Our extension consists
of one class, RectangleArea, that computes the areas of rectangles:
public final class RectangleArea {
public static int area(java.awt.Rectangle r) {
return r.width * r.height;
}
}
This class has a single method, area, that takes an instance of
java.awt.Rectangle and returns the rectangle's area.
Suppose that you want to test RectangleArea with an application
called AreaApp:
import java.awt.*;
public class AreaApp {
public static void main(String[] args) {
int width = 10;
int height = 5;
Rectangle r = new Rectangle(width, height);
System.out.println("The rectangle's area is "
+ RectangleArea.area(r));
}
}
This application instantiates a 10 x 5 rectangle, and then
prints out the rectangle's area using the
RectangleArea.area method.
Running AreaApp Without the Extension Mechanism
Let's first review how you would run the AreaApp application
without using the extension mechanism. We'll assume that the
RectangleArea class is bundled in a JAR file named area.jar.
The RectangleArea class is not part of the Java platform, of
course, so you would need to place the area.jar file on the
class path in order to run AreaApp without getting a runtime
exception. If area.jar was in the directory /home/user,
for example, you could use this command:
java -classpath .:/home/user/area.jar AreaApp
The class path specified in this command contains both the current
directory, containing AreaApp.class, and the path to
the JAR file containing the RectangleArea package. You would
get the desired output by running this command:
The rectangle's area is 50
Running AreaApp by Using the Extension Mechanism
Now let's look at how you would run AreaApp by using the
RectangleArea class as an extension.
To make the RectangleArea class into an extension, you place the
file area.jar in the lib/ext directory of the JRE.
Doing so automatically gives the RectangleArea the status of being
an installed extension.
With area.jar installed as an extension, you can run
AreaApp without needing to specify the class path:
java AreaApp
Because you're using area.jar as an installed extension, the
runtime environment will be able to find and to load the
RectangleArea class even though you haven't specified it on
the class path. Similarly, any applet or application being run by any user
on your system would be able to find and use the RectangleArea class.