Java Class Loader addDirectoryToClassLoader(ClassLoader loader, File directory)

Here you can find the source of addDirectoryToClassLoader(ClassLoader loader, File directory)

Description

add Directory To Class Loader

License

Apache License

Declaration

public static boolean addDirectoryToClassLoader(ClassLoader loader, File directory) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {
    public static boolean addDirectoryToClassLoader(ClassLoader loader, File directory) {
        try {// ww w.  java  2 s . c o  m
            ClassLoader rootLoader = getRootLoader(loader);
            if (rootLoader == null) {
                return false;
            } else {
                URL url = directory.toURI().toURL();
                Method method = rootLoader.getClass().getMethod("addURL", URL.class);
                method.invoke(rootLoader, url);
                return true;
            }

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private static ClassLoader getRootLoader(ClassLoader loader) {

        if (loader == null) {
            return null;
        } else if (isRootClassLoader(loader)) {
            return loader;
        } else {
            return getRootLoader(loader.getParent());
        }
    }

    private static boolean isRootClassLoader(ClassLoader loader) {
        return (loader != null) && isRootLoaderClass(loader.getClass());
    }

    private static boolean isRootLoaderClass(Class<?> loaderClass) {
        return (loaderClass != null) && ((loaderClass.getName() == "groovy.lang.GroovyClassLoader")
                || (loaderClass.getName() == "org.codehaus.groovy.tools.RootLoader")
                || isRootLoaderClass(loaderClass.getSuperclass()));
    }
}

Related

  1. addFileToSystemClassLoader(String s)
  2. createClassloader(File libDir, ClassLoader cl)
  3. createClassLoader(File root)
  4. createClassLoader(final String[] cpEntries)