您尝试从不同类调用 main 方法的方式不正确,我想这就是它不起作用的原因。另一件事是你的问题不是很清楚,从你的代码看起来好像你正在尝试调用同一个类的 main 方法。
但据我了解,您有两个项目,并且您正试图从第一个项目的主要方法调用第二个项目的主要方法。
以下是实现该功能的代码片段。
第二个项目的主要方法(将成为图书馆的那个)
public class second {
public static void main(String[] args) {
System.out.println("This statement comes from the main method in the jar .");
System.out.println("total params passed are: " + args.length);
for (String string : args) {
System.out.println("param is: " + string);
}
}
}
第一个项目的主方法(将调用库的主方法)
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
System.out.println("This statement is from main method in the program.");
/**
* This is the class name. and it needs to be correct.
* You do not need to mention project name or library name.
* newpackage is a package in my library and second is a class name in that package
*/
final Class _class = Class.forName("newpackage.second");
//here we mention which method we want to call
final Method main = _class.getMethod("main", String[].class);
//this are just parameters if you want to pass any
final String[] params = {"one", "two", "three"};
try {
//and finally invoke the method
main.invoke(null, (Object) params);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex);
}
下面是添加库项目后我的项目结构的样子
