How to create a pluginable Java program? How to create a pluginable Java program? java java

How to create a pluginable Java program?


I've done this for software I've written in the past, it's very handy. I did it by first creating an Interface that all my 'plugin' classes needed to implement. I then used the Java ClassLoader to load those classes and create instances of them.

One way you can go about it is this:

File dir = new File("put path to classes you want to load here");URL loadPath = dir.toURI().toURL();URL[] classUrl = new URL[]{loadPath};ClassLoader cl = new URLClassLoader(classUrl);Class loadedClass = cl.loadClass("classname"); // must be in package.class name format

That has loaded the class, now you need to create an instance of it, assuming the interface name is MyModule:

MyModule modInstance = (MyModule)loadedClass.newInstance();


Look into OSGi.

On one hand, OSGi provides all sorts of infrastructure for managing, starting, and doing lots of other things with modular software components. On the other hand, it could be too heavy-weight for your needs.

Incidentally, Eclipse uses OSGi to manage its plugins.


I recommend that you take a close look at the Java Service Provider (SPI) API. It provides a simple system for finding all of the classes in all Jars on the classpath that expose themselves as implementing a particular service. I've used it in the past with plugin systems with great success.