Java在运行时加载外部类

时间:2012-03-27 21:38:08

标签: java class url methods jar

我还有另一个问题,答案就是我。我希望在运行时从外部jar中获取一个类,并从中获取一个方法并传递一个参数。我下面的代码当前打开jar并抓取类并运行方法但是当我尝试传递一个参数时,该方法运行但我得到一个InvocationTargetException。有什么想法吗?

这是我的代码:

    String path = "test.jar";
    URL[] classes = {new File(path).toURI().toURL()};
    URLClassLoader child = new URLClassLoader (classes, this.getClass().getClassLoader());
    try {
        Class classToLoad = Class.forName("testClass", true, child);
        Method method = classToLoad.getDeclaredMethod ("testMethod", String.class);
        Object instance = classToLoad.newInstance();
        Object result = method.invoke(instance, new String("Test from method!"));
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

这是它抛出的错误:

Test from method!
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at Load.loadJar(LoadTerrem.java:33)
    at Load.<init>(LoadTerrem.java:18)
    at Load.main(LoadTerrem.java:13)
Caused by: java.lang.NullPointerException
    at MenuSingleplayer.LoadWorlds(MenuSingleplayer.java:210)
    at MenuSingleplayer.setup(MenuSingleplayer.java:89)
    at M0.LoadGame(M0.java:76)
    ... 7 more

正如您所看到的,该方法执行,打印出传递给它的字符串,但然后在该行上抛出错误:

Object result = method.invoke(instance, new String("Test from LoadTerrem!"));

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:3)

问题出在MenuSingleplayer.LoadWorlds方法中。它说NPE发生在那里。与反射无关。没关系:

Caused by: java.lang.NullPointerException
at MenuSingleplayer.LoadWorlds(MenuSingleplayer.java:210)

答案 1 :(得分:3)

当调用的方法(在您的情况下为testMethod)抛出异常时,抛出InvocationTargetException。来自文档:

  

InvocationTargetException是一个经过检查的异常,它包装了被调用的方法或构造函数抛出的异常。

从您的堆栈跟踪判断(“由 - 引起” - 确切)看起来testMethod会导致MenuSingleplayer.LoadWorlds被调用,从而引发NullPointerException。这个NullPointerException向上传播,直到它到达反射调用,此时它被包裹在InvocationTargetException中。