我正在尝试运行从另一个 jar 加载的一些方法,该方法返回一个整数,然后我想将其返回到另一个类并将其传递给我的逻辑。
我使我的方法加载类非常简单,如下所示:
public class ModuleLoader {
private Class<?> cls;
public void initializeCommandModule(Module m) throws Exception {
URL url = this.getURL(m.getJar());
this.cls = this.loadClass(m.getMainClass(), url);
}
public int execute(Module m, ArrayList<String> args) throws Exception {
Method method = this.cls.getDeclaredMethod("execute", ArrayList.class);
return (int) method.invoke(this.cls.newInstance(), 1);
}
public int respond(ArrayList<String> args) throws Exception {
Method method = this.cls.getDeclaredMethod("response", ArrayList.class);
return (int) method.invoke(this.cls.newInstance(), 1);
}
private Class<?> loadClass(String cls, URL url) throws ClassNotFoundException, IOException {
URLClassLoader loader = new URLClassLoader(new URL[]{url});
Class<?> toReturn = loader.loadClass(cls);
loader.close();
return toReturn;
}
private URL getURL(String jar) throws MalformedURLException {
return new File(jar).toURI().toURL();
}
}
Run Code Online (Sandbox Code Playgroud)
看一下execute(Module m, ArrayList<String> args)方法,这一行抛出错误:
return (int) method.invoke(this.cls.newInstance());
Run Code Online (Sandbox Code Playgroud)
我加载的 jar 库如下所示:
public class Test {
public int execute(ArrayList<String> i) {
System.out.println("Hello world!");
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么当我运行该方法时会抛出以下异常?
Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
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 ben.console.modules.ModuleLoader.execute(ModuleLoader.java:24)
at ben.console.CommandProcessor.process(CommandProcessor.java:37)
at ben.console.Console.listen(Console.java:25)
at ben.console.Console.main(Console.java:31)
Run Code Online (Sandbox Code Playgroud)
谢谢指教!
您忘记将参数传递给方法调用。
return (int) method.invoke(this.cls.newInstance(), myArrayList);
Run Code Online (Sandbox Code Playgroud)
您还可以使用 null 参数进行调用:
return (int) method.invoke(this.cls.newInstance(), (Object[])null);
Run Code Online (Sandbox Code Playgroud)