如果scala代码编译为在JVM上运行的.class
文件,为什么不能通过java
或java -jar
运行它们?
我使用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文件需要什么?