繁体   English   中英

ClassLoader仅可从类路径运行,而不能从URL运行

[英]ClassLoader only working from classpath and not url

因此,我试图从链接加载文件并在内存中运行它。 一切工作正常,但仅当.jar位于项目的类路径中时。 我的代码如下:

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都只会在项目的类路径中运行。 如何从链接加载文件,而不是从类路径中加载文件?

这是因为您没有将.jar URL传递给URLClassloader。 在您的代码中,它需要一个空数组,所以我不知道如何从您的jar文件中加载类。

这是如何修改代码以将jar URL传递给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});

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM