我们如何使用java代码帮助设置类路径而不是手动?
答案 0 :(得分:8)
我们做不到。必须在java虚拟机的启动时设置类路径。我们无法从正在运行的应用程序中更改它。
可以从不在类路径上的位置和jar文件加载类。使用URLClassloader
从已知(文件)URL加载单个类,或者实现自己的类加载器以获得更多魔力。
答案 1 :(得分:3)
如果要编辑用于从其他路径加载jar文件的类路径,那么使用URLClassLoader(如建议的@Andreas_D)代码后面的类路径可能对您有所帮助:
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