简体   繁体   English

在 Java 程序中编译和运行 Scala 文件

[英]Compile and Run Scala File within a Java Program

I am working on a Java program that takes a Scala program in a text file, compiles it (inside Java), then runs it (also inside Java).我正在开发一个 Java 程序,它在文本文件中接收 Scala 程序,编译它(在 Java 内部),然后运行它(也在 Java 内部)。 I could not figure out a clean way to implement this.我想不出一个干净的方法来实现这个。 To compile, I tried to use code as shown below:为了编译,我尝试使用如下所示的代码:

import scala.collection.JavaConversions;
import scala.tools.nsc.Global;
import scala.tools.nsc.Settings;

Global g = new Global(new Settings());
Global.Run run = g.new Run();
List<String> fileNames = new ArrayList<String>(Arrays.asList("Hello.scala"));

run.compile(JavaConversions.asScalaBuffer(fileNames).toList());

However, I get an error (reduced for clarity):但是,我收到一个错误(为清楚起见减少了):

error: error while loading Object, Missing dependency 'object scala in compiler mirror', required by C:\Program Files\Java\jdk1.7.0_79\jre\lib\rt.jar(java/lang/Object.class)

I did not understand what was causing this or how to fix.我不明白是什么导致了这个或如何解决。 As a temporary workaround, I tried compiling the Scala code externally and calling that in Java via:作为临时解决方法,我尝试在外部编译 Scala 代码并通过以下方式在 Java 中调用它:

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -cp scala-library.jar;. Hello");

While I think the code runs, it is not interactive with the Java program as I would like.虽然我认为代码可以运行,但它并不像我希望的那样与 Java 程序交互。 For example, when running the Scala program (inside Java) if the Scala program wanted the user to type a string into the console, the Java program should do the same essentially.例如,在运行 Scala 程序(在 Java 内部)时,如果 Scala 程序希望用户在控制台中键入一个字符串,则 Java 程序本质上应该做同样的事情。

Any guidance is appreciated.任何指导表示赞赏。

The easiest way is probably just to use a tiny wrapper library that takes care of things like class-paths etc. For example, there is a small library Twitter Util-Eval ( source ).最简单的方法可能只是使用一个小型包装库来处理类路径等。例如,有一个小型库Twitter Util-Eval ( source )。

Here is an example:下面是一个例子:

package foo;

import com.twitter.util.Eval;

public class Test {
  public static void main(String[] args) {
    final Eval eval = new Eval();
    final int result = eval.apply("3 + 4", true);
    System.out.println("Result: " + result);
  }
}

If you want to bake your own compiler and runner wrapper, this involves a bit more, you will need to compile to virtual files and then load them into a class loader (see for example here and here ).如果您想烘焙自己的编译器和运行器包装器,这涉及更多内容,您需要编译为虚拟文件,然后将它们加载到类加载器中(参见此处此处的示例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM