0
所以我試圖從鏈接加載文件並在內存中運行它。一切正常工作正常,但只有當.jar在項目的類路徑中。我的代碼如下:ClassLoader只從類路徑工作,而不是url
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.JarInputStream;
public class Main {
public static URL getURL(String string) throws MalformedURLException {
try {
return new URL(string);
} catch (MalformedURLException x) { return new URL("file:" + string); }
}
public static void main(String args[]) throws Exception {
String jarLocation = "http://www.google.ca/file.jar";
URL url = new URL(jarLocation);
getURL(jarLocation);
JarInputStream jis = new JarInputStream(url.openStream());
String main = jis.getManifest().getMainAttributes().getValue("Main-Class");
String classpaths[] = jis.getManifest().getMainAttributes().getValue("Class-Path").split(" ");
for (String classpath: classpaths) {
getURL(classpath);
}
URLClassLoader loader = new URLClassLoader((new URL[0]));
Class<?> cls = loader.loadClass(main);
Thread.currentThread().setContextClassLoader(loader);
Method m = cls.getMethod("main", new Class[]{new String[0].getClass()});
m.invoke(null, new Object[]{args});
}
}
的問題是,無論聯繫是什麼,會的.jar只有當它是在項目的類路徑運行。 如何從鏈接加載文件,而不是從類路徑中加載文件?