views:

226

answers:

5

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?

A: 
public class SomeClass { 
    static {
        System.out.println("Being called with the class is loaded");
        initialize();
    }
    static void initialize(){}
}

Is that your question?

OscarRyz
Nice :) But how can I load and run a class from a file? The class won't come with the application, the user will "download" the addon and add it to the "addons" folder. The application will load all the addons when started.
Baversjo
Yeap. I actually didn't quite catch what your question was in first place. Class.forName is pretty much the way to go.
OscarRyz
+3  A: 

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.

Stephan202
This worked! I don't know if this is the "correct" way to do it, and I'm happy for feedback. Keep in mind that this is only for loading one class: Class classfoo = Class.forName("addonclass"); Object foo = null; Object[] foo2 = null; classfoo.getMethod("initialize").invoke(foo, foo2);
Baversjo
Happy to hear it works! Myself I'm also interested in feedback about the "correct" way. I have the feeling a more elegant way exists...
Stephan202
"I have a feeling a more elegant way exists." No, this is the documented correct way to do it.
Jay
+1  A: 

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.

Michael Myers
You only need your own class loader if you want a non-standard way to load the class. If the class exists as a ".class" file in a folder on the class path, the standard class loader will do it.If you want to, say, download the class from the Internet behind the scenes, then you'd need a custom class loader.
Jay
A: 

Another nice way to realize addons is java.util.Serviceloader. Have a look at the javadocs, they explain the principle.

Lars
+1  A: 

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". ...

adrian.tarau