我需要在运行时用Java加载一个jar文件,我有这个代码,但它没有加载任何jar,我不知道怎么样,有人可以告诉我为什么?我有JVM 8和NetBeans 8,目的是创建一个程序,可以将jar文件作为Windows的插件加载。
package prueba.de.classpath;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class PruebaDeClasspath {
public static void main(String[] args) {
try {
Class.forName("PluginNumeroUno");
} catch (ClassNotFoundException e) {
System.out.println("Not Found");
}
try {
URLClassLoader classLoader = ((URLClassLoader) ClassLoader
.getSystemClassLoader());
Method metodoAdd = URLClassLoader.class.getDeclaredMethod("addURL",
new Class[]{URL.class});
metodoAdd.setAccessible(true);
File file = new File("plugins/PrimerPlugins.jar");
URL url = file.toURI().toURL();
System.out.println(url.toURI().toURL());
metodoAdd.invoke(classLoader, new Object[]{url});
} catch (Exception e) {
e.printStackTrace();
}
try {
Class.forName("PluginNumeroUno");
System.out.println("ok");
} catch (ClassNotFoundException e) {
System.out.println("Not Found");
}
}
}
答案 0 :(得分:1)
尝试创建新的类加载器,而不是强制转换系统类加载器。
删除此行:
URLClassLoader classLoader = ((URLClassLoader) ClassLoader.getSystemClassLoader());
并创建新的加载器并使用如下:
File file = new File("plugins/PrimerPlugins.jar");
URLClassLoader classLoader = new URLClassLoader(new URL[]{file.toURI().toURL()},
PruebaDeClasspath.class.getClassLoader());
Class.forName("prueba.de.classpath.PluginNumeroUno", true, classLoader); //fully qualified!
请注意,要加载的班级名称必须完全合格。
您也不必动态强制addURL()
公开。