Search code examples
javajardynamic-loading

load jars dynamically and execute arbitrary code in them


I have a java console app that I'm writing, and I want people to be able to write plugins for it and then to distribute those plugins as jars. I want users to be able to drop a plugin (jar) into a "plugins" folder, restart the app, and have the plugin loaded and running. I don't want the user to have to specify a class/method to execute for the plugin or anything like that.

I can load the jars with a wildcard classpath to the "plugins" directory, but I need some way for those plugins to register themselves with the application by running a register() method that each plugin will need to define somewhere. How can the plugin (jar) specify where(package and class) it's register() method is defined so my app will know to call it?

I realize that OSGi can accomplish this, but this is a fairly small application and I would prefer not to use OSGi if a simpler solution exists.

Background:

These plugins register events from the app that they want to handle. The user will be able to disable the handling of specific events on a per plugin basis, so the configuration for these plugins will be stored in the app's database. When a plugin registers itself, the app will check the database to see if a configuration exists for that plugin, and if not it will create a new default configuration for it in the database.


Solution

  • Presumably your register method is part of a Plugin interface?

    If so you could implement a custom ClassLoader to detect classes implementing this interface. Then subsequently use a Listener based approach to notifying whatever object manages your plugins of the classes' presence.