I have a Java project that needs a "addon" interface. I was thinking about loading some kind of class files having default methods like initialize()
and shutdown()
that will be called after the class has been loaded into the application. Is this the way to do it? How would I approach this problem?
views:
226answers:
5public class SomeClass {
static {
System.out.println("Being called with the class is loaded");
initialize();
}
static void initialize(){}
}
Is that your question?
Have a look at the Class class, specifically the forName method, which allows you to reference a class by name. Any class in the path can be loaded like this. Whether reloading is possible I don't know.
In any case, each class that you want to dynamically load would have to implement your custom AddOn
interface, thus implementing initialize
and shutdown
.
First, you will need a ClassLoader
; you can get the current one with getClass().getClassLoader()
, but then your addon classes must be in the classpath. You'll probably want to create a custom classloader that searches your addon directory.
Once you've got the ClassLoader
, you can use it to load a class. This gives you a Class
object; you can then use reflection to call the initialize()
method if it is present.
Another nice way to realize addons is java.util.Serviceloader. Have a look at the javadocs, they explain the principle.
If you look at something more sophisticated, you can try : http://jpf.sourceforge.net.
... JPF provides a runtime engine that dynamically discovers and loads "plug-ins".A plug-in is a structured component that describes itself to JPF using a "manifest". ...