从java程序调用另一个类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18780888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:59:58  来源:igfitidea点击:

call another class from java program

javaclasscall

提问by Rahul Mehrotra

I have 2 classes one is a simple one

我有 2 个班级,一个是简单的班级

Sample.java

示例.java

public class Sample {
  public static void main(String args[]) {

    System.out.println("Hello World!!!!!");
  }
}

Other one is something like this

另一个是这样的

Main.java

主程序

public class Main
{  
  public static void main(String[] args) throws Exception
  {
     Runtime.getRuntime().exec("java Sample");
  }
}

I am basically trying to run the Main.java program to call Sample.java in a new command prompt...that is a new cmd that should open and print the output of Sample.java...how should I do this...???

我基本上是在尝试运行 Main.java 程序以在新的命令提示符下调用 Sample.java ......这是一个新的 cmd 应该打开并打印 Sample.java 的输出......我应该怎么做...... .???

采纳答案by stan

Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"cd <where_the_Sample_is> && javac Sample.java && java Sample\"");

or if the class is already compiled:

或者如果该类已经编译:

Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"cd <where_the_Sample_is> && java Sample\"");

回答by Siddh

Compile the two together, and then from Sample,

将两者编译在一起,然后从Sample,

Main.main(args);

will do the trick. You don't need to import since you're in the same package. Note the linked tutorial. http://docs.oracle.com/javase/tutorial/java/package/index.html

会做的伎俩。您不需要导入,因为您在同一个包中。请注意链接的教程。 http://docs.oracle.com/javase/tutorial/java/package/index.html

回答by Macrosoft-Dev

I am using eclipse. The class files are placed in the bin directory located under the projects directory. The below code starts command prompt, changes directory to bin and issues java Sample command. You can edit it up to your requirement.

我正在使用日食。类文件放置在位于项目目录下的 bin 目录中。下面的代码启动命令提示符,将目录更改为 bin 并发出 java 示例命令。您可以根据需要对其进行编辑。

Runtime.getRuntime().exec("cmd.exe /c cd \"bin\" & start cmd.exe /k \"java Sample\"");

Runtime.getRuntime().exec("cmd.exe /c cd \"bin\" & start cmd.exe /k \"java Sample\"");

回答by Manitra

You can use this code:

您可以使用此代码:

public class Main {
    public static void main(String[] args) throws Exception {
        Class<Sample> clazz = Sample.class;
        Method mainMethod = clazz.getMethod("main", String[].class);
        String[] params = null;
        mainMethod.invoke(null, (Object) params);
    }
}