可以在运行时将目录添加到类路径吗? [英] Can a directory be added to the class path at runtime?

查看:125
本文介绍了可以在运行时将目录添加到类路径吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了更好地理解Java中的工作原理,我想知道是否可以在运行时动态地将目录添加到类路径中。

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.

例如,如果我使用java -jar mycp.jar启动 .jar 并输出 java.class.path 属性,我可能会得到:

For example, if I launch a .jar using "java -jar mycp.jar" and output the java.class.path property, I may get:

java.class.path: '.:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java'

现在可以在运行时修改此类路径以添加另一个目录? (例如在使用位于我要添加的目录中的 .jar 对类进行第一次调用之前)。

Now can I modify this class path at runtime to add another directory? (for example before making the first call to a class using a .jar located in that directory I want to add).

推荐答案

您可以使用以下方法:

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});
}

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

这篇关于可以在运行时将目录添加到类路径吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆