Including Java Classes and Running Them at Runtime
I have a Java project that needs an "addon" interface. I was thinking about loading some class files that have default methods such as initialize()
and shutdown()
that will be called after the class has been loaded into the application. Is this the way to do it? How can I approach this problem?
a source to share
Look at the class Class , in particular forName , which allows you to refer to a class by name. Any class in the path can be loaded as follows. Whether a reboot is possible, I don't know.
In any case, every class you want to load dynamically must implement its own user interface AddOn
, thus implementing initialize
and shutdown
.
a source to share
You will need first ClassLoader
; you can get the current s getClass().getClassLoader()
, but then your addon classes must be on the classpath. You might want to create a custom classloader that looks for your addons directory.
Once you get it ClassLoader
, you can use it to load the class . This gives you an Class
object; you can use reflection to call the method initialize()
if present.
a source to share
If you look at something a little more complex you can try: http://jpf.sourceforge.net .
... JPF provides an execution engine that dynamically detects and loads "plugins". A plugin is a structured component that describes itself in JPF using a "manifest" ....
a source to share
Another nice way to implement addons is with java.util.Serviceloader . Take a look at the javadocs, they explain the principle.
a source to share