2014-07-06 23 views
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只有當它是在項目的類路徑運行。 如何從鏈接加載文件,而不是從類路徑中加載文件?

回答

1

這是因爲你是而不是將你的.jar URL傳遞給URLClassloader。在你的代碼中它需要一個空的數組,所以我不知道如何從你的jar文件中加載類。

下面是如何修改代碼以罐子網址傳遞到URLClassLoader的一個例子:

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"; 
     List<URL> urls = new ArrayList<>(); 
     URL url = new URL(jarLocation); 
     urls.add(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) { 
      urls.add(getURL(classpath)); 
     } 
     URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()])); 
     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}); 

    } 

}