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, 
    IllegalAccessException{
        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.

4 Comments »

  1. Wim Deblauwe said,

    Just what I was looking for! Thank you for posting this.

    regards,

    Wim

  2. Ray said,

    Hi,

    The codes you shown were able only to load the class once,
    may you modify it so reloading (many times) is possible ?

    Ray

  3. […] is a followup to my previous post on this subject. Recently I needed to load some modules (which all implement the […]

  4. I’ve searched all over for this information.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: