执行.jar文件时,`scala`不需要-jar,而`java`则不需要-jar?

时间:2020-03-17 23:49:57

标签: java scala

我想知道为什么在执行.jar文件时scala不需要-jar,而java却需要scala target/some.jar java -jar target/someother.jar

例如:

scala

我看一下java shell脚本,它以如下方式调用execCommand \ "${JAVACMD:=java}" \ $JAVA_OPTS \ "${java_args[@]}" \ "${classpath_args[@]}" \ -Dscala.home="$SCALA_HOME" \ $OVERRIDE_USEJAVACP \ $WINDOWS_OPT \ scala.tools.nsc.MainGenericRunner "$@"

scala

target/some.jar作为"$@"的一部分java传递到java是否正确,因此target/some.jar命令没有前缀-jarglmulti(y ~ ., data=data, level=2, fitfunction=glm, crit="aic", confsetsize=128, method = "g", plotty = T, chunks = 8) 一起使用?

谢谢。

1 个答案:

答案 0 :(得分:5)

分析MainGenericRunner的源代码后,我们看到scala赛跑者试图猜测用户的意图

  def runTarget(): Option[Throwable] = howToRun match {
    case AsObject =>
      ObjectRunner.runAndCatch(settings.classpathURLs, thingToRun, command.arguments)
    case AsScript if isE =>
      ScriptRunner(settings).runScriptText(combinedCode, thingToRun +: command.arguments)
    case AsScript =>
      ScriptRunner(settings).runScript(thingToRun, command.arguments)
    case AsJar    =>
      JarRunner.runJar(settings, thingToRun, command.arguments)
    case Error =>
      None
    case _  =>
      ...
  }

其中howToRun可能会呼叫guessHowToRun

  private def guessHowToRun(target: String): GenericRunnerCommand.HowToRun = {
    if (!ok) Error
    else if (io.Jar.isJarOrZip(target)) AsJar
    else if (ScalaClassLoader.classExists(settings.classpathURLs, target)) AsObject
    else {
      val f = io.File(target)
      if (!f.hasExtension("class", "jar", "zip") && f.canRead) AsScript
      else {
        Console.err.println("No such file or class on classpath: " + target)
        Error
      }
    }
  }

我们可以通过提供-howtorun标志来明确表示:

scala -howtorun:jar some.jar

例如,如果我们在java -jar中指定主类,则也可以通过build.sbt运行scala应用程序

Compile / mainClass := Some("example.MyMain")

并执行sbt assembly,然后可以像这样执行在target/下产生的胖子罐

java -jar myapp-assembly.jar