簡體   English   中英

用戶URLClassLoader可以“即時”加載jar文件

[英]User URLClassLoader to load jar file “on the fly”

好的,基本上,我嘗試使用此處描述的方法JarFileLoader加載一個包含與將在類路徑上使用的類相同的類的jar(類名將是動態的,因此我們可以將任何具有任何類,程序將通過在主行中解析文本文件來加載它)。

問題是當我調試並檢查URLClassLoader對象時

protected Class<?> findClass(final String name)

線:

Resource res = ucp.getResource(path, false);

getResource()在參數中找不到類名。

有人已經嘗試過以這種方式加載jar文件嗎?

謝謝。

裝載機

public class JarFileLoader extends URLClassLoader {
    public JarFileLoader() {
        super(new URL[] {});
    }

    public JarFileLoader withFile(String jarFile) {
        return withFile(new File(jarFile));
    }

    public JarFileLoader withFile(File jarFile) {
        try {
            if (jarFile.exists())
                addURL(new URL("file://" + jarFile.getAbsolutePath() + "!/"));
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException(e);
        }
        return this;
    }

    public JarFileLoader withLibDir(String path) {
        Stream.of(new File(path).listFiles(f -> f.getName().endsWith(".jar"))).forEach(this::withFile);
        return this;
    }
}

主要:

public static void main(String[] args) {
    new Initializer();
    JarFileLoader cl = new JarFileLoader();
    cl = cl.withFile(new File("libs/dpr-common.jar"));
    try {
        cl.loadClass("com.*****.atm.dpr.common.util.DPRConfigurationLoader");
        System.out.println("Success!");
    } catch (ClassNotFoundException e) {
        System.out.println("Failed.");
        e.printStackTrace();
    } finally {
        try {
            cl.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

這是我使用的測試類。 當我調試URLClassLoader時,我可以在第三個循環中看到jar文件的路徑(類路徑和您在此處添加的URL上的循環),但是仍然找不到資源(並且無法調試類URLClassPath,所以不知道getRessource做什么)究竟)。

好吧,我從以下問題中得到答案: 如何從目錄動態加載所有jar?

並從一開始就更改URL的一部分,直到完成它的大部分工作為止。

因此,一個示例可能是:

String path = "libs/dpr-common.jar";
if (new File(path).exists()) {
    URL myJarFile = new File(path).toURI().toURL();
    URL[] urls = { myJarFile };
    URLClassLoader child = new URLClassLoader(urls);
    Class DPRConfLoad = Class.forName("com.thales.atm.dpr.common.util.DPRConfigurationLoader", true, child);
    Method method = DPRConfLoad.getDeclaredMethod("getInstance");
    final Object dprConf = method.invoke(DPRConfLoad);
}

我所有的時間都浪費在搜索上,而這是一個錯誤的例子...仍然不明白為什么他們使用愚蠢的URL,例如“ jar:file ...”等。

感謝大家。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM