在运行时将文件添加到 java 类路径 [英] Adding files to java classpath at runtime
问题描述
是否可以在运行时将文件(不一定是 jar 文件)添加到 java 类路径.具体来说,该文件已经存在于类路径中,我想要的是我是否可以将此文件的修改副本添加到类路径中.
Is it possible to add a file (not necessarily a jar file) to java classpath at runtime. Specifically, the file already is present in the classpath, what I want is whether I can add a modified copy of this file to the classpath.
谢谢,
推荐答案
您只能向类加载器添加文件夹或 jar 文件.所以如果你只有一个类文件,你需要先把它放到合适的文件夹结构中.
You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.
这里 是一个相当丑陋的 hack,它添加到 SystemClassLoader运行时:
Here is a rather ugly hack that adds to the SystemClassLoader at runtime:
import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;
public class ClassPathHacker {
private static final Class[] parameters = new Class[]{URL.class};
public static void addFile(String s) throws IOException {
File f = new File(s);
addFile(f);
}//end method
public static void addFile(File f) throws IOException {
addURL(f.toURL());
}//end method
public static void addURL(URL u) throws IOException {
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysloader, new Object[]{u});
} catch (Throwable t) {
t.printStackTrace();
throw new IOException("Error, could not add URL to system classloader");
}//end try catch
}//end method
}//end class
反射是访问受保护方法addURL
所必需的.如果有 SecurityManager,这可能会失败.
The reflection is necessary to access the protected method addURL
. This could fail if there is a SecurityManager.
这篇关于在运行时将文件添加到 java 类路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!