首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“动态”加载jar文件的用户URLClassLoader

“动态”加载jar文件的用户URLClassLoader
EN

Stack Overflow用户
提问于 2018-09-03 16:04:10
回答 1查看 457关注 0票数 0

好的,基本上,我尝试使用这里描述的方法JarFileLoader来加载一个jar,其中包含一个类,它的使用方式与它在类路径中的使用方式相同(类名将是动态的,这样我们就可以添加具有任何类的任何jar,程序将通过解析主行中的文本文件来加载它)。

问题是,当我调试和检查URLClassLoader对象时

代码语言:javascript
复制
protected Class<?> findClass(final String name)

行:

代码语言:javascript
复制
Resource res = ucp.getResource(path, false);

getResource()在参数中找不到类名。

是否有人已经尝试以这种方式加载jar文件?

谢谢。

加载器:

代码语言:javascript
复制
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;
    }
}

Main:

代码语言:javascript
复制
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上的循环),但是仍然没有找到ressource (并且不能调试类URLClassPath,所以不知道getRessource到底做了什么)。

EN

回答 1

Stack Overflow用户

发布于 2018-09-03 23:21:24

好的,我从这个问题中得到答案:How to load all the jars from a directory dynamically?

并更改URL部分的开始与它的方式,在长的部分它的工作。

因此,一个示例可以是:

代码语言:javascript
复制
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);
}

我所有的时间都浪费在搜索上,而这是错误的例子……仍然不明白为什么他们使用像"jar:file...“这样愚蠢的URL。等。

谢谢大家。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52145561

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档