我创建了一个应在运行时加载的 Talend 作业。我正在代码中动态加载作业 jar 。加载后,我需要调用一个执行该作业的函数。
为了执行它,我遵循了 this 的答案问题。但是当调用该函数时,我收到java.lang.NoSuchMethodException
。我认为问题出在函数的参数类型定义中,但我很难正确定义它。
这是我的代码:
String args[] = new String[7];
args[0] = "myParams";
File jobJar = new File("myjar.jar");
URL [] urls = new URL[1];
urls[0] = jobJar.toURI().toURL();
Class<?>[] params_type = new Class[]{args.getClass()}; //is it correct?
URLClassLoader child = new URLClassLoader(urls , this.getClass().getClassLoader());
Class classToLoad = Class.forName ("com.my.myTalendClass", true, child);
Method method = classToLoad.getDeclaredMethod ("runJobInTOS", params_type);
Object instance = classToLoad.newInstance();
Object result = method.invoke(instance,new Object[]{ args });
函数runJobInTOS
接收一个字符串数组作为参数
最佳答案
为什么使用
Object result = method.invoke(instance,new Object[]{ args });
但不是
Object result = method.invoke(instance,args);
在代码中,您将二维数组传递给方法,而不是普通的字符串数组
关于java - 如何正确定义运行时加载的类的函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18743391/