Dynamically load a jar at runtime

A short post but I figured I would throw it up here before I lose my code. There are a couple of different ways that you can load jar’d code at runtime but here is a simple solution that I found to work very easily.

       File myJar = new File("myJar.jar");
       URL url = myJar.toURI().toURL();

       Class[] parameters = new Class[]{URL.class};

        URLClassLoader sysLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
        Class sysClass = URLClassLoader.class;
        try
        {
            Method method = sysClass.getDeclaredMethod("addURL", parameters);
            method.setAccessible(true);
            method.invoke(sysLoader,new Object[]{ url });

            Constructor cs = ClassLoader.getSystemClassLoader().loadClass("com.example.MyClass").getConstructor(); 
            MyInterface instance = (MyInterface)cs.newInstance();
            instance.someFunction();
        }
        catch(Exception ex)
        {
            System.err.println(ex.getMessage());
        }

In the code example above the jar at the location pointed to by the url object is dynamically loaded and an instance of the class com.example.MyClass is created that conforms to a known interface MyInterface. This could be used in a situation where you are loading plugins that use a common interface example.