Java ClassPath Add addToClasspath(File file)

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

Description

Adds the specified file to the classpath dynamically

License

Open Source License

Parameter

Parameter Description
file - The file to add to the classpath

Return

True if the file was added, false otherwise.

Declaration

public static boolean addToClasspath(File file) 

Method Source Code

//package com.java2s;
/**/*from  w ww  .j  ava  2s  . com*/
 * This class is the core Single Player Commands class. It handles all input and controls all
 * output
 * 
 * @author simo_415 Copyright (C) 2010-2012 simo_415 - (http://bit.ly/spcmod)
 * 
 *         This file is part of Single Player Commands.
 * 
 *         Single Player Commands is free software: you can redistribute it and/or modify it under
 *         the terms of the GNU Lesser General Public License as published by the Free Software
 *         Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 *         Single Player Commands is distributed in the hope that it will be useful, but WITHOUT ANY
 *         WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 *         PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 *         You should have received a copy of the GNU Lesser General Public License along with
 *         Single Player Commands. If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;

import java.lang.reflect.*;
import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    public static boolean DEBUG = false;

    /**
     * Adds the specified file to the classpath dynamically
     * 
     * @param file - The file to add to the classpath
     * @return True if the file was added, false otherwise.
     */
    public static boolean addToClasspath(File file) {
        if (!file.exists()) {
            return false;
        }
        URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Class<URLClassLoader> sysclass = URLClassLoader.class;
        try {
            Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
            method.setAccessible(true);
            method.invoke(sysloader, new Object[] { file.toURI().toURL() });
        } catch (Throwable t) {
            t.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * Prints the given stacktrace
     * 
     * @param throwable The exception to print
     */
    public static void printStackTrace(Throwable throwable) {
        if (DEBUG) {
            throwable.printStackTrace();
        }
    }
}

Related

  1. addDirToClasspath(File directory)
  2. addDirToClasspath(File directory)
  3. addPathToClassPath(String s)
  4. addToClasspath(File f)
  5. addToClassPath(File file)
  6. addToClassPath(String s)
  7. addToClassPath(Vector cpV, String dir)