Wednesday, July 15, 2015

URL based class loading in Java and dynamically adding directories to java classpath @ runtime

1. How to load a class dynamically at runtime by using URLClassLoader .

// Main Method
        try { 
            URL url = new URL("file:///<path to my jar file>.jar");
            URLClassLoader urlClassLoader = new URLClassLoader(
                    new URL[] { url });
            Class clazz = urlClassLoader
                    .loadClass("org.sample.package.ClassName");
            Object obj = clazz.newInstance();
            System.out.println(obj.toString());
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

Explanation:

Create a URL object of the jar file 
Pass the URL object to the URLClassLoader
Call loadCLass on the URLClassLoader object , specifying the class name with the package hierarchy , as argument.
Create a new Instance of the loadedClass
Refer to newInstance()for more details.
Use the obj of the loaded class to call a method.

Exceptions to be handled:

IllegalAccessException - if the class or its nullary constructor is not accessible.

InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.

ClassNotFoundException - If the class was not found

MalformedURLException - if an unknown protocol is specified.

                                   ###########################################

2. How to dynamically add directories from a fileSystem to Java ClassPath @ Runtime 

// Main Method
        try {
            File file = new File("absolute/path/to/the/directory");
            Method method = URLClassLoader.class.getDeclared
                  Method("addURL", new Class[] { URL.class});
            method.setAccessible(true);
            method.invoke(ClassLoader.getSystemClassLoader(),
                    new Object[] { file.toURI().toURL() });
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

Explanation:

Create a file object for the directory to be added to the classpath.
Get the method object of addUrl method of the class URLClassLoader
For more details see this.
Reflected object should suppress Java language access Checking when it is used , hence the setAccessible(true).
Invoke the method , the first argument is the class invoking the method and the following arguments are sent as arguments to the invoked method in orderly fashion. 

Exceptions to be handled:

NoSuchMethodException - if a matching method is not found.

SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException 

Refer this

MalformedURLException - if an unknown protocol is specified.

I hope you learned something new today .

No comments:

Post a Comment