0

我正在使用 Netbeans 7.1.2,我正在尝试运行我的 Java 应用程序,其中 Main 类尝试从不同的项目调用另一个 Main 类,

public class Main {
    public static void main(String[] args) {
        com.XXXX.XXXX.main.Main.main(new String [] {

当我尝试在 netbeans 中设置类路径时,在项目属性中找不到库选项。

在此处输入图像描述

我的项目中也没有库文件夹。那么现在如何设置类路径来访问另一个项目的主类。

提前致谢,

4

1 回答 1

1

您尝试从不同类调用 main 方法的方式不正确,我想这就是它不起作用的原因。另一件事是你的问题不是很清楚,从你的代码看起来好像你正在尝试调用同一个类的 main 方法。

但据我了解,您有两个项目,并且您正试图从第一个项目的主要方法调用第二个项目的主要方法。

  • 第一步是将您的第二个项目构建为jar文件。然后关闭这个项目并忘记它。

  • 第二步是开发你的第一个项目并将你的第二个项目的 jar 作为库添加到这个项目中。一旦完成,它只是简单的编码。

以下是实现该功能的代码片段。

第二个项目的主要方法(将成为图书馆的那个)

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);
    }

下面是添加库项目后我的项目结构的样子

于 2014-08-14T13:56:36.010 回答