动态添加Jar到Classpath时的NoSuchMethodException

时间:2013-10-24 03:10:01

标签: java exception runtime

我正在尝试使用THIS方法在运行时动态地将Jar添加到我的程序类路径中,因为它似乎适用于很多人。使用addPlugin()时会抛出NoSuchMethodException(在下面的代码中注明)。

有人可以告诉我我缺少什么才能让这个工作吗?我对此并不太熟悉,我之前尝试过这样做。

public final class PluginLoader {
    private static final Class[] _PARAMS = new Class[] {URL.class};

    public static void addPlugin(File plugin) throws PluginException {
        URLClassLoader plLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
        Class plClass = URLClassLoader.class;
        try {
                Method m = plClass.getDeclaredMethod("addPlugin", _PARAMS); //ERROR HERE
                m.setAccessible(true);
                m.invoke(plLoader, new Object[] {plugin.toURI().toURL()});
        } catch (Exception ex) {
                ex.printStackTrace();
                throw new PluginException("ERROR: Could not add plugin '" + plugin.getName() + "' to System ClassLoader");
        }
    }
}

用法:

PluginLoader.addPlugin(new File("../path/to/jar.jar"));
Constructor<?> cs = ClassLoader.getSystemClassLoader().loadClass("my.main.class.Main").getConstructor(String.class);

1 个答案:

答案 0 :(得分:0)

变化:

Method m = plClass.getDeclaredMethod("addPlugin", _PARAMS);

为:

Method m = plClass.getDeclaredMethod("addURL", _PARAMS);
相关问题