March 11, 2008

Dynamic class loading in Java

Posted in Java at 12:03 by theBlackDragon

This is a repost of an older article I wrote back in 2006 (yes, I had to use the wayback machine to get it back ;))

I was looking for a way to dynamically load plugins from (at development time) unknown jars the other day and after some searching (nowadays they call that Googling I guess?) I found the solution in Java’s ClassLoader class, in URLClassLoader to be precise. This task turned out to be amazingly simple.

I just defined an interface called Plugin that all the Plugins should implement so that I can cast whatever I get from the ClassLoader to this interface.

So without further ado, here’s the code (yes, only 6 lines of actual code):

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

This gets me a new ClassLoader with all the plugins in a given directory. findAllJars() is a oneliner grabbing all jars from my projects “plugin” directory using a FilenameFilter to filter the Jars from the cruft 😉

I can then load a plugin like this:

    public static void load(String p)
    throws ClassNotFoundException, InstantiationException, 
        Class c = classLoader.loadClass(p);
        Plugin plug = (Plugin) c.newInstance();

This uses the ClassLoader to load an instance of the dot-notated classname I pass in (eg. be.lair.remes.plugin.ircplugin.IRCPlugin), I then use this Class to create an instance which I then cast to the correct type.

Notwithstanding the fact that I didn’t find a great deal of example of this on the net it was amazingly simple to get working. Makes me wonder why people always need to pick on Java.