如何使用Java运行一罐已编译的scala .class文件?

时间:2019-03-18 03:47:29

标签: java scala jar jvm sbt

TL; DR

如果scala代码编译为在JVM上运行的.class文件,为什么不能通过javajava -jar运行它们?

MVCE

我使用sbt创建了一个新的scala项目并将其打包到jar中。

$ sbt new scala/scala-seed.g8
[info] Set current project to knoble (in build file:/Users/Knoble/)
[info] Set current project to knoble (in build file:/Users/Knoble/)

A minimal Scala project.

name [Scala Seed Project]: hello

Template applied in /Users/Knoble/./hello

$ cd hello/
$ ls
build.sbt  project/   src/
$ sbt package
[info] Loading project definition from /Users/Knoble/hello/project
[info] Updating ProjectRef(uri("file:/Users/Knoble/hello/project/"), "hello-build")...
[info] Done updating.
[info] Compiling 1 Scala source to /Users/Knoble/hello/project/target/scala-2.12/sbt-1.0/classes ...
[info] Done compiling.
[info] Loading settings for project root from build.sbt ...
[info] Set current project to hello (in build file:/Users/Knoble/hello/)
[info] Updating ...
[info] Done updating.
[info] Compiling 1 Scala source to /Users/Knoble/hello/target/scala-2.12/classes ...
[info] Done compiling.
[info] Packaging /Users/Knoble/hello/target/scala-2.12/hello_2.12-0.1.0-SNAPSHOT.jar ...
[info] Done packaging.
[success] Total time: 4 s, completed 17 mars 2019 22:12:53

java进行静音不起作用

scala解释器可以很好地运行它。但是,java运行者不能:

$ scala target/scala-2.12/hello_2.12-0.1.0-SNAPSHOT.jar
hello
$ java -jar target/scala-2.12/hello_2.12-0.1.0-SNAPSHOT.jar
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: scala/Function0
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
    at java.lang.Class.getMethod0(Class.java:3018)
    at java.lang.Class.getMethod(Class.java:1784)
    at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: scala.Function0
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more

我读了in another SO answer,我需要包括scala库依赖项。我尝试了以下变体(相同的错误):

$ java -classpath $(printf '%s:' /usr/local/Cellar/scala/2.12.8/libexec/lib/*.jar) -jar target/scala-2.12/hello_2.12-0.1.0-SNAPSHOT.jar
$ java -classpath $(printf '%s:' $(basename /usr/local/Cellar/scala/2.12.8/libexec/lib/*.jar)) -jar target/scala-2.12/hello_2.12-0.1.0-SNAPSHOT.jar
$ java -classpath /usr/local/Cellar/scala/2.12.8/libexec/lib/scala-library.jar -jar target/scala-2.12/hello_2.12-0.1.0-SNAPSHOT.jar

运行此jar文件需要什么?

0 个答案:

没有答案