Java ClassPath Add addDirToClasspath(File directory)

Here you can find the source of addDirToClasspath(File directory)

Description

Adds the jars in the given directory to classpath

License

Open Source License

Parameter

Parameter Description
directory a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void addDirToClasspath(File directory) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    private static final Class[] parameters = new Class[] { URL.class };

    /**/*from  w ww  . j  ava 2 s . c om*/
     * Adds the jars in the given directory to classpath
     * @param directory
     * @throws IOException
     */
    public static void addDirToClasspath(File directory) throws IOException {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            for (File file : files) {
                addURL(file.toURI().toURL());
            }
        }
    }

    /**
     * Add URL to CLASSPATH
     * @param u URL
     * @throws IOException IOException
     */
    public static void addURL(URL u) throws IOException {
        URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        URL urls[] = sysLoader.getURLs();

        for (URL url : urls) {
            if (url.toString().equalsIgnoreCase(u.toString())) {
                //URL is already in the CLASSPATH
                return;
            }
        }

        Class sysclass = URLClassLoader.class;

        try {
            Method method = sysclass.getDeclaredMethod("addURL", parameters);
            method.setAccessible(true);
            method.invoke(sysLoader, new Object[] { u });
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException t) {
            System.out.println("URL error : " + t.getMessage());
            throw new IOException("Error, could not add URL to system classloader");
        }
    }
}

Related

  1. addClasspath(String path)
  2. addClassPath2ClassLoader(ClassLoader cl, String path)
  3. addClasspathEntries(Collection cpEntries)
  4. addClassPathItems(String[] cpItems)
  5. addDirToClasspath(File directory)
  6. addPathToClassPath(String s)
  7. addToClasspath(File f)
  8. addToClassPath(File file)
  9. addToClasspath(File file)