Java ClassPath Add addToClasspath(File f)

Here you can find the source of addToClasspath(File f)

Description

Adds a given file to the classpath.

License

Open Source License

Parameter

Parameter Description
f File to be added

Declaration

public static void addToClasspath(File f) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015 Pablo Pavon Mari?o.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 * /*from   w  w w . j  av  a 2s .  c o m*/
 * Contributors:
 *     Pablo Pavon Mari?o - initial API and implementation
 ******************************************************************************/

import java.io.File;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;

import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    /**
     * Adds a given file to the classpath.
     * 
     * @param f File to be added
     * @since 0.3.1
     */
    public static void addToClasspath(File f) {
        try {
            Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
            addURL.setAccessible(true);

            URL url = f.toURI().toURL();
            ClassLoader cl = ClassLoader.getSystemClassLoader();
            addURL.invoke(cl, new Object[] { url });
        } catch (NoSuchMethodException | SecurityException | MalformedURLException | IllegalAccessException
                | IllegalArgumentException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. addClasspathEntries(Collection cpEntries)
  2. addClassPathItems(String[] cpItems)
  3. addDirToClasspath(File directory)
  4. addDirToClasspath(File directory)
  5. addPathToClassPath(String s)
  6. addToClassPath(File file)
  7. addToClasspath(File file)
  8. addToClassPath(String s)
  9. addToClassPath(Vector cpV, String dir)