Developing an application with plugin support in Java

I studied how to develop an application that can load plugins. So far I have seen that this can be done by defining an interface, and plugins implement it.

However, my current problem is with loading plugins when they are packaged in Jars. Is there a โ€œbetterโ€ way to do this?

The current logic that I think of is to force each plugin and inside their Jar to look for a class that implements the interface. But I do not know how to do this. I think that this logic may not be very good, but I could not find useful information on this particular topic.

** Edit1: ** Adding additional information: The supposed plugins would be Jar files contained in the subdirectory where the main Jar application will be located, for example:

Application folder | - Hunting and fishing | - Communication | - Questions and answers | - Questions and answers | | - Steve's_plugin.jar

Etc.

I expect the application to be able to load all plugins inside the folder at runtime. Thus, in the code it will only be known that the plugin folder must exist, and there must be Jars in such a folder.

Say I have a plugin interface:

interface Plugin { public void run(); } 

Plugins will be identified by a class that implements such an interface, for example

 class Plugin1 implements Plugin { //attributes and other methods @override public void run() { //something happens here } } class Plugin2 implements Plugin { //attributes and other methods @override public void run() { //something happens here } } 

The application should be compiled only once and be able to download any plugins added to the folder during its execution. So that the application can load any plugin, do I need to set Jar content rules, for example, the package name and the class that implements the interface? Or is it expected that the class that implements the plugin interface can be in any package inside the Jar and have any name?

This is a more general approach to what I would like to do with such plugins. In short, I plan to create an application that will have tabs, and each plugin will provide the interface and functionality of each tab. I try to do this because I want to be able to support each tab separately and do not want to recompile the entire application due to changes in only one component that does not affect the others at all.

+5
source share
1 answer

Get a list of plugin banners:

 File[] jars = new File("Plugins").listFiles(); 

Then use the code of this answer to load all classes from the JAR file , but run it once for each file in jars whose name ends with ".jar" . In the lower body of the cycle, after

 Class c = cl.loadClass(className); 

continue

 if (Plugin.class.isAssignableFrom(c)) { Plugin plugin = (Plugin) c.newInstance(); // And then, do something with the plugin here } 

I share @Mifeet's security concern - you can use the SecurityManager to limit the ability to use plugin code.

+2
source

All Articles