I want to make an application that can dynamically load plug-ins but I’ve not found any literature on Internet.
The difficult thing is: I don’t know the name in advance.
For example I’ve a Plugin interface:
public interface Plugin {
public static Plugin newPlugin();
public void executePlugin(String args[]);
}
So that every Class implementing Plugin in the jar file are instantiated in a list:
Method method = classToLoad.getMethod ("newPlugin");
mylist.add(method.invoke(null);
- First problem is, I cannot have a static method in an interface.
- Second problem is, I don’t know how to find all classes that implement an interface
Thanks for your help.
So it seems like you want to dynamically discover Classes that implement a specific interface (e.g.,
Plugin) at runtime. You have basically two choices for this:ServiceLoader)Since there are many good tutorials on osgi (also small ones), I will not detail that here. To use Java’s internal discovery process, you need to do the following:
META-INF/services/package.PluginYou must use the full package qualifier herePluginin that jar-fileService discovery is done like this:
There are more details here: http://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html
As for static methods in interfaces: not possible. The semantics of that would also be somewhat weird as static methods are accessible without an instance of a class, and interfaces just define the methods, without any functionality. Thus, static would allow to call
Interface.doSomething()whereas the interface does not define any functionality, this leads just to confusion.edit:
added description what should be in the meta-file