free web hosting | website hosting | Business Hosting | Free Website Submission | shopping cart | Promoter Online | php hosting
affordable web hosting Pets web page hosting web hosting website hosting web hosting service web hosting web host
Plug-in Modules in Java

Plug-in Modules in Java

"Plug-in" modules are classes that can be 'plugged-in', that is, modules that can be dynamically loaded by the host Java application. The advantage of using the plug-in classes is that the host application does not have to specify the names of the available plug-in classes at compile time. The plug-in classes can be compiled separately and can be added or removed.

This page explains how to create an abstract class Plugin class, derive plug-in classes, and how to call the derived plug-in classes. The plug-in classes can be compiled separately, and loaded by the host application dynamically.

Plugin class is the base class for all derived plug-in classes. The Plugin drived plug-in classes define execute() function which can be called from the host application regardless of the type of plug-in classes.


   public abstract class Plugin
   {
       public abstract void execute();   
   }

Now let's define the derived SamplePlugin class. This SamplePlugin class only has the execute() function that prints out "Sample Plug-in".


   public class SamplePlugin extends Plugin
   {
       public void execute()
       {
           System.out.println("Sample Plug-in");   
       }
   }

At the host application side, call Class.forName(String) to load the plug-in classes, and newInstance() function to instantiate them. Here shows the callPlugin(String) function that loads and instantiates the SamplePlugin class dynamically, and then calls execute() member function of the plug-in class.


   public void callPlugin(String pluginName)
   {
        try
            {
                Class pluginClass=Class.forName(pluginName);
                if(pluginClass!=null)
                    {
                        Plugin plugin=(Plugin)pluginClass.newInstance();   
                        plugin.execute();
                    }
            }
        catch(Exception e)
            {
                System.out.println("Please install "+pluginName);
            }
   }

This summarizes the above procedure.

  1. Create an abstract class Plugin.
  2. Derive plug-in classes from Plugin. Define execute() member function.
  3. Load the plug-in classes dynamically and instantiate the plug-in class by calling Class.forName(String) and newInstance().
  4. Call execute().

Return to Home Page
Erica Asai
Last Modified: Fri Sep 03 11:33:11 2004