且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

可以在运行时将目录添加到类路径吗?

更新时间:2023-01-04 14:31:04

您可以使用以下方法:

URLClassLoader.addURL(URL url)

但是你需要用反射做这个,因为方法是 protected

But you'll need to do this with reflection since the method is protected:

public static void addPath(String s) throws Exception {
    File f = new File(s);
    URL u = f.toURL();
    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});
}

请参阅反思。特别是反思的缺点