1

在 Helloworld.java 类的 main 函数中,我创建了一个字符串或一个对象。然后,我创建了另一个类 HelloAnotherClass.java。我想将我的变量从 Helloworld main() 传递给 HelloAnotherClass.java 的主函数。

package helloworld;
        public class HelloAnotherClass {
           public static void main(String[] args) throws IOException, ParseException {
        //... for example print passed variables
        }

如何使用参数或其他数据结构将变量从 HelloWorld main() 发送到 HelloAnotherClass main(),然后再将其返回到 HelloWorld.java?简而言之,我想使用另一个 java 类的 main() 函数作为 HelloWorld 类中的函数。

那是我写的代码示例

    HelloWorld { 
    /** * @param args the command line arguments */ 
    public static void main(String[] args) { 
    HelloAnotherClass.main("example"); 
    } 

public class HelloAnotherClass { 
    public static void main(String coming) throws IOException, ParseException { 
System.out.println(coming); 
    }
4

4 回答 4

1

这取决于你想如何运行其他类

如果你想在当前的 JVM 中运行它,那么你可以通过显而易见的方式来执行它:

  • 创建一个包含参数的字符串数组。
  • main以数组作为参数调用方法。

如果你想在一个新的 JVM 中运行它,那么你可以使用 System.exec(...) (或等效的)和一个命令字符串,就像你java自己从命令行运行一样。(如果参数字符串包含空格,你想使用特定的 Java 安装,你想使用相同的 JVM 选项,等等......它会更复杂。)

这两种方法各有优缺点:

  • 调用另一个类main可以让您快速“启动”时间,但是:

    1. 另一个类不会有一组独立的System.in/out/err流,因为它与原始main类共享静态,
    2. 如果它调用System.exit()整个JVM就会退出,
    3. 如果它行为不端,原来的main类可能无法摆脱它,依此类推。
  • 启动单独的 JVM 会导致启动时间明显变慢,但子 JVM 将无法干扰父 JVM。


顺便说一句,您最初尝试失败的原因是您传递的是字符串而不是字符串数组。编译器不会让你这样做......

于 2012-10-14T06:13:22.677 回答
0

如果您正在运行两个独立的程序并希望它们交换数据,请阅读有关进程间通信的内容。

于 2012-10-14T06:11:04.513 回答
0

默认main参数为String[]. 更新HelloAnotherClass如下:

public class HelloWorld { 

   /** * @param args the command line arguments */ 
   public static void main(String[] args) { 
        HelloAnotherClass.main(new String[]{"example"}); 
   }
}

如果您尝试在HelloAnotherClass课堂上打印参数,则如下所示:

public class HelloAnotherClass { 

  public static void main(String[] coming) throws IOException, ParseException {  
    System.out.println(coming[0]); 
  }
}

如果您想拥有另一个带有Stringas 参数的 main 方法,也可以这样做:

public class HelloWorld { 

    /** * @param args the command line arguments */ 
    public static void main(String[] args) { 
       HelloAnotherClass.main("example"); 
    }
 }

 public class HelloAnotherClass { 

    public static void main(String coming) throws IOException, ParseException {  
       System.out.println(coming); 
    }
 }

如果您正在寻找其他/其他详细信息,请告诉我。

于 2012-10-14T06:25:22.610 回答
0

这是 HelloWorld,有一些参数,(我通过了“Hello Crazy World”)

public static void main(String args[]) {
    //call static main method of Main2 class
    HelloAnotherWorld.main(args);
      //Modifcation made on Main2 is reflected
    System.out.println(args[1].toString());
}

}

这是HelloAnotherWorld

public static void main(String args[]) {        
    args[1]="foobar";
}

由于在 HelloAnotherWorld 中 main 是静态的,因此您可以将 main 方法称为 HelloAnotherWorld.main("array goes here"); 另请注意,main 返回 void,因此任何传递原语并返回它的尝试都是不成功的,除非您重载了 main 方法。

于 2012-10-14T06:25:58.867 回答