scala 如何从java程序的main方法调用Scala程序的main方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16673919/
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-10-22 05:18:32  来源:igfitidea点击:

How to call main method of a Scala program from the main method of a java program?

javascala

提问by yAsH

Suppose I have a Scala class and a Java class in a Java project and the scala class is like below

假设我在 Java 项目中有一个 Scala 类和一个 Java 类,Scala 类如下所示

class Sam {

  def main(args: Array[String]): Unit = {
    println("Hello")
  }

}

How can I call it's main method from the main method of a java program which is present in the same project

如何从同一项目中存在的java程序的main方法调用它的main方法

回答by Martin Ellis

Typically, main methods are staticin Java, and in an objectin Scala. This allows you to run them from the command line. Your code defines a class, not an object.

通常,主要方法static在 Java 中,object在 Scala 中。这允许您从命令行运行它们。您的代码定义了一个class,而不是一个object

I'd suggest changing your Scala code to:

我建议将您的 Scala 代码更改为:

object Sam {
  def main(args: Array[String]): Unit = {
    println("Hello")
  }
}

You can then call this from your Java main method as follows:

然后,您可以从 Java 主方法中调用它,如下所示:

class Foo  {
    public static void main(String[] args) {
        Sam.main(args);
    }
}