使用URLClassLoader动态加载JAR? [英] Dynamically load a JAR using URLClassLoader?

查看:1781
本文介绍了使用URLClassLoader动态加载JAR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序需要能够在运行时动态加载JAR - 在环顾四周之后我相信它使用URLClassLoader,但我不知道如何让它工作。 JARopenup.jar与程序位于同一目录中。

I have a program which needs to be able to dynamically load JARs at runtime - after looking around I beleive this uses URLClassLoader, but I'm not sure how to get it to work. The JAR "openup.jar" is in the same directory as the program.

理想情况我希望能够在没有JAR的情况下加载此JAR必须在其中指定每个单独的类。

Ideally I would like to be able to load this JAR without having to specify each individual class inside it.

推荐答案

我成功使用的内容:

@SuppressWarnings("unchecked")
public void addURL(URL u) throws IOException {
    URLClassLoader sysLoader = (URLClassLoader) ThisClass.class.getClassLoader();
    URL urls[] = sysLoader.getURLs();
    for (int i = 0; i < urls.length; i++) {
        if (urls[i].toString().equalsIgnoreCase(u.toString())) {
            return;
        }
    }
    Class sysclass = URLClassLoader.class;
    try {
        Method method = sysclass.getDeclaredMethod("addURL", parameters);
        method.setAccessible(true);
        method.invoke(sysLoader, new Object[] { u });
    } catch (Throwable t) {
        throw new IOException("Error, could not add URL to system classloader");
    }
}

我应该如何在运行时动态加载Jars?

这篇关于使用URLClassLoader动态加载JAR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆