I'm writing a java app that does some data processing, and I want to be able to load new filters at runtime and add them to a filter chain in some arbitrary order.
So... I was thinking...
What if I made an interface called "FilterStructure" and implemented it in a set of real filters with arbitrary names, then serialized those classes into easily transported files. The user would then load those files at runtime and select which of them they wanted to execute, as well as open up their settings panels for altering parameters.
Is there a better way to do this?
I haven't really thought about this topic much. I guess my intuition would be to use reflection. Then your "easily transported" files would in fact be normal compiled .class files, rather than serialised equivs.
Would it be possible to write the filters in groovy instead of Java? Then they could be loaded dynamically and you can do whatever you want with the code.
I don't think you want to use serialization though. I'd say you could define the interface as you suggest, and then ensure that implementations of the interface are on the classpath. Then you could load instances of those classes dynamically (I tihnk you can use the default classloader, but you might have to use a special one) at runtime.
Haven't tried it, but it might be worth a look http://jpf.sourceforge.net/
JPF is the way to go if you are intersted in using a standardized framework.
Or, you can create your own. It's a peice of cake, no reflection required (infact avoid reflection as far as possible). It basically boils down to creating a Plugin inteface, that all your plugins should implement. This interface should provide a mechanism through which your plugins can register themselves with your program, in addition to other stuff.
Then it is only a matter of creating a custom ClassLoader to load the plugins.
The way I did it was jar -cf the files and in the manifest include the plugin's class (the class that implements that interface you defined). You can use any custom delimter here.. I used "plugin-class"
Then when your program runs, scan the plugins directory for .jar files (or whatever your .extension is) and look up the manifest. Read the plugin-class property. If it exists, then add that jar to your classloader's classpath, and load the respective class.
As for the custom ClassLoader, it might be easier to just use the java.net.URLClassLoader
Ah, that's really informative. Thanks!