Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a pluginable Java program?

I want to create a Java program that can be extended with plugins. How can I do that and where should I look for?

I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow.


Although I do like Eclipse RCP, I think it's too much for my simple needs.

Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it.

But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible.

like image 240
pek Avatar asked Aug 24 '08 23:08

pek


People also ask

How do you make Hello World in Java?

The signature of the main method in Java is: public static void main(String[] args) { ... .. ... } System.out.println("Hello, World!");

How do I create a .java file?

To create a new Java class or type, follow these steps: In the Project window, right-click a Java file or folder, and select New > Java Class. Alternatively, select a Java file or folder in the Project window, or click in a Java file in the Code Editor.


2 Answers

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(); 
like image 129
Steve M Avatar answered Oct 13 '22 11:10

Steve M


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.

like image 42
David Koelle Avatar answered Oct 13 '22 09:10

David Koelle