I am attempting to make a game using java, and I need a plugin system for the server...
How might I make it so that there is a folder named plugins that the users can simply drop jar files in there and I can call functions within those jar files all at once?
This is implying that a community would make plugins that I don't know about (so i need to have it run all plugins even if I don't know the plugins name)
(I would appreciate it if I didn't need to use someone else's framework like jspf)
-
3While the accepted answer is great, I would personally be very grateful for another answer that doesn't use a framework. The reason for this is (1) I want to understand how this is done and (2) there might be an instance in which I require something that JSPF doesn't provide.Paul Draper– Paul Draper2013年03月27日 20:20:07 +00:00Commented Mar 27, 2013 at 20:20
1 Answer 1
Writing your own plug-in infrastructure is fun, but totally unneccesary. It's a solved problem and you're not going to write a higher quality one than one that already exists and is proven in the field. I'd say choose your battles.
I've tried out JSPF before and found it incredibly easy to use. And this coming from someone who has done exactly what you're trying to do: I've made my own plug-in infrastructure (for basically the same purpose: to load mini-games dynamically) from scratch, writing the classloading and framework myself. And if I were to do it again, I would use a framework like JSPF without hesitation.
To load all classes from jars in a directory that adhere to a certain interface (say Game), it's as easy as:
PluginManager pm = PluginManagerFactory.createPluginManager();
pm.addPluginsFrom(new File("plugins/").toURI());
Collection<Game> games = new PluginManagerUtil(pm).getPlugins(Game.class);
IIRC the only requirement on implementers of Game is that it be tagged with the @PluginImplementation annotation.
Edit
And then:
for ( Game game : games ) {
game.someMethod();
}