March 18, 2011

Dynamic class loading in Java, using constructors

Posted in Java at 15:10 by theBlackDragon

This is a followup to my previous post on this subject. Recently I needed to load some modules (which all implement the “Plugin” interface in my example) in a project using constructor arguments, this is how to go about it. Most of the previous post stays valid, you still need a ClassLoader that “knows” the jars you want to load.

        URL[] jarFiles = findAllJars();
        if(jarFiles != null)
            classLoader = URLClassLoader.newInstance(jarFiles);

Then you need to load the Class (without instantiating it, of course) and create a Constructor object, then pass the appropriate arguments to the Constructor object and instantiate the class using this object and the actual arguments.

This is how the previous article’s example looks like when using arguments:

    public static void load(String p)
    throws ClassNotFoundException, InstantiationException,
        Class cl = classLoader.loadClass(p);
        Constructor c = cl.getConstructor(String.class);
        Plugin plug = (Plugin) c.newInstance("myArgument");

The argument p is the class to be loaded (for example be.lair.plugins.MyPlugin). The argument(s) to the getConstructor call are the types of parameters the constructor expects and the last line actually provide these arguments and instantiates the class.

On a related note, maybe I should look into unloading these classes after they have been loaded, if at all possible. I’ve never had a use case for trying to do this but it might be an interesting exercise.