My linux world » Java – Plugin

Java - Plugin


In this short example, we will create an “easy” plugin manager.

Contents

Interface

We must create an interface. Our plugins will implement this interface.

public interface Plugin {
 
    /**
     *  Execute something.
     */
    public void execute();
 
    /**
     * @return the class name.
     */
    public String getClassName();
}

Plugin 1

Now we can create our first plugin :

public class Plugin1 implements Plugin {
 
	private static final String NAME="plugin-1";
 
	/* (non-Javadoc)
	 * @see Plugin#execute()
	 */
	public void execute() {
		System.out.println("I am in "+NAME);
	}
 
	/* (non-Javadoc)
	 * @see Plugin#getClassName()
	 */
	public String getClassName() {		
		return this.getClass().getName();
	}
 
}

Plugin 2

Now we can create our second plugin :

public class Plugin2 implements Plugin {
 
	private static final String NAME="plugin-2";
 
	/* (non-Javadoc)
	 * @see Plugin#execute()
	 */
	public void execute() {
		System.out.println("I am in "+NAME);
	}
 
	/* (non-Javadoc)
	 * @see Plugin#getClassName()
	 */
	public String getClassName() {		
		return this.getClass().getName();
	}
 
}

Get the plugin class list

Reflections reflections = new Reflections(Plugin.class);
Set<Class<? extends Plugin>> pluginClasses = reflections.getSubTypesOf(pluginInterface);

Load plugins

In the example below, we got the plugin class list. It is ONLY classes (so it is NOT instance !).
We must create an instance for each plugin to load them :

for(Class<? extends Plugin> clazz : classes) {
  Plugin plugin = (Plugin) clazz.newInstance();
}

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.