• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to do dynamic plugins?  RSS feed

 
Alex Rickabaugh
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have a Java program that defines a few interfaces or base classes, and someone else writes some classes that make use of them, is there any way my application can, at runtime, load that person's .jar file and get instances of those classes? Bascially, I'm trying to write a plugin framework for my IRC bot.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes. If you specify a specific format for making it known to your application what classes there are to load.

Simplest would be a propertiesfile listing them all with specific keys you define.
More flexible would be an xml file which can link the classes to descriptions (for display in menus maybe) and metadata (interfaces implemented maybe, things like that).

You can then use an abstractfactory pattern to instantiate the correct class on that key.
Something like (errorchecking code, imports, etc. omitted for brevity)


By defining a specific method for initialisation in your interface and calling that in the factory you can work around the limitation that getInstance() always calls a no-argument constructor.

This version uses a properties file, using an XML file is only slightly more complex.
[ December 29, 2004: Message edited by: Jeroen Wenting ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For more depth on the ideas behind this, Google for Dependency Inversion and/or Dependency Injection. Here's something I did for my team on DIP that may be interesting.

I use this kind of thing all the time. Users of the plugin factory look like this:

I can add new key and classname pairs through configuration. I use a rude hack to modify the classpath from configuration, too, so plugins can come from external jars or directories.

Eclipse takes a neat approach and scans all subdirectories under a certain location for plugin descriptor XML files. You install plugins by copying files into that directory and automagically they are there!

For real cool factor, think about how to refresh all the configuration without stopping and restarting the program. I wish I'd done that!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!