don't dream your life, live your dreams !
In this short example, we will create an “easy” plugin manager.
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(); } |
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(); } } |
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(); } } |
Reflections reflections = new Reflections(Plugin.class); Set<Class<? extends Plugin>> pluginClasses = reflections.getSubTypesOf(pluginInterface); |
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.
admin