我还有另一个问题使答案难以理解。我希望在运行时从外部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!"));
有任何想法吗?谢谢!
最佳答案
当被调用的方法(在您的情况下为InvocationTargetException
)引发异常时,将引发testMethod
。从文档:
InvocationTargetException是一个已检查的异常,它包装了由调用的方法或构造函数引发的异常。
从堆栈跟踪(准确地说是“由...引起的”部分)来看,它看起来像testMethod
导致MenuSingleplayer.LoadWorlds
被调用,从而引发一个NullPointerException
。此NullPointerException
一直传播到到达反射调用为止,此时将其包装在InvocationTargetException
中。