可以在运行时将目录添加到类路径吗?
为了更好地理解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});
}
请参阅反思。特别是反思的缺点