Can a directory be added to the class path at runtime?

前端 未结 3 1822
执念已碎
执念已碎 2020-12-01 03:50

In order to better understand how things works in Java, I\'d like to know if I can dynamically add, at runtime, a directory to the class path.

For example, if I laun

3条回答
  •  借酒劲吻你
    2020-12-01 04:04

    Update 2014: this is the code from the accepted answer, by Jonathan Spooner from 2011, slightly rewritten to have Eclipse's validators no longer create warnings (deprecation, rawtypes)

    //need to do add path to Classpath with reflection since the URLClassLoader.addURL(URL url) method is protected:
    public static void addPath(String s) throws Exception {
        File f = new File(s);
        URI u = f.toURI();
        URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Class urlClass = URLClassLoader.class;
        Method method = urlClass.getDeclaredMethod("addURL", new Class[]{URL.class});
        method.setAccessible(true);
        method.invoke(urlClassLoader, new Object[]{u.toURL()});
    }
    

提交回复
热议问题