Java ClassLoader addFile(File file)

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

Description

Add a file to the classpath.

License

Open Source License

Parameter

Parameter Description
file the file to add

Return

true if the file was successfully added; false otherwise.

Declaration

public static boolean addFile(File file) 

Method Source Code


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

import java.io.File;
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 };

    /**//w  w w .  ja  v  a2s.  co  m
     * Add a file to the classpath.
     * @param file the file to add
     * @return true if the file was successfully added; false otherwise.
     */
    public static boolean addFile(File file) {
        try {
            return addURL(file.toURI().toURL());
        } catch (Exception ex) {
            return false;
        }
    }

    /**
     * Add a URL to the classpath.
     * @param url the URL to add
     * @return true if the URL was successfully added; false otherwise.
     */
    public static boolean addURL(URL url) {
        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 });
            return true;
        } catch (Throwable t) {
            return false;
        }
    }
}

Related

  1. add(File file)
  2. addDirectory(File directory)
  3. AddFile(File f)
  4. addFile(String s)
  5. createDir(String pathName)
  6. createDirectoryLoader(String directory)
  7. CreateLogbackXML(OutputStream out)