我有一个程序,需要能够在运行时动态加载JARs -在环顾四周之后,我相信它使用了URLClassLoader,但我不知道如何使它工作。JAR "openup.jar“与程序位于同一个目录中。
--理想的--我希望能够加载这个JAR,而不必指定其中的每个单独的类。
发布于 2011-01-11 11:21:51
我成功地使用了:
@SuppressWarnings("unchecked")
public void addURL(URL u) throws IOException {
URLClassLoader sysLoader = (URLClassLoader) ThisClass.class.getClassLoader();
URL urls[] = sysLoader.getURLs();
for (int i = 0; i < urls.length; i++) {
if (urls[i].toString().equalsIgnoreCase(u.toString())) {
return;
}
}
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysLoader, new Object[] { u });
} catch (Throwable t) {
throw new IOException("Error, could not add URL to system classloader");
}
}在How should I load Jars dynamically at runtime?中确实提供了一个几乎相同的解决方案
发布于 2021-10-12 14:26:44
在这里,我将解释创建jar然后在另一个项目中动态加载jar的整个过程:
创建jar的步骤:
在任意IDE(Eclipse).
包装newJar.com.example;
公共类MyClass {
public MyClass() {
// TODO Auto-generated constructor stub
}
public void helloWorld() {
System.out.println("Hello from the helloWorld");
}}
动态加载jar的步骤:
公共类CustomClass {
公共CustomClass() { // TODO自动生成的构造函数存根}
公开无效getCall(文件myJar) {
尝试{ URLClassLoader loader =新URLClassLoader(new URL[] { myJar.toURI().toURL() } )、URLClassLoader类classToLoad = Class.forName("newJar.com.example.MyClass“、true、loader)、System.out.println(ClassToLoad)、方法方法=classToLoad.getDeclaredMethod(”helloWorld“)、对象实例=classToLoad.newInstance()、对象结果=method.invoke(实例);{ // TODO自动生成的catch块();}
}
公共静态空洞主(String[] args) { // TODO自动生成的方法存根
文件myJar =新文件(“jar路径");//"D:\ECLIPSE\myjar.jar”CustomClass cls =新CustomClass();cls.getCall(myJar);
}
}
这就是它如何利用jar的方法,如果jar位于服务器上,那么就可以给出服务器路径而不是本地路径。
https://stackoverflow.com/questions/4656957
复制相似问题