![]() |
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.
Plugin.
Plugin. Define execute() member function.
Class.forName(String) and newInstance().
execute().