67,549
社区成员




public static void addJarFileToClasspath(File jarFile, boolean addMainfestClasspath) throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
List<URL> urls = new ArrayList<URL>(5);
urls.add(jarFile.toURI().toURL());
if (addMainfestClasspath) {
JarFile jf = new JarFile(jarFile);
Manifest mf = jf.getManifest();
if (mf != null) {
String cp = mf.getMainAttributes().getValue("class-path");
if (cp != null) {
for (String cpe : cp.split("//s+")) {
File lib = new File(jarFile.getParentFile(), cpe);
urls.add(lib.toURI().toURL());
}
}
}
jf.close();
}
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<? extends URLClassLoader> sysclass = URLClassLoader.class;
Method method = sysclass.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
for (URL url : urls) {
method.invoke(sysloader, url);
}
}