14

我希望我的 Scala 代码将 Scala 类作为输入,编译并执行该类。如何以编程方式调用 Scala 编译器?我将使用最新的 Scala 版本,即 2.10。

4

2 回答 2

13

工具箱

我认为调用 Scala 编译器的正确方法是通过Overview中记录的反射 API 来实现。具体来说,通过“符号、树和类型”中工具箱部分的解析创建String树讨论了解析为Tree使用ToolBox. 然后你可以调用eval()等。

scala.tools.nsc.Global

但正如 Shyamendra Solanki 所写,实际上你可以驱动 scalacGlobal完成更多工作。我已经编写了CompilerMatcher,因此我可以使用示例代码编译生成的代码来进行集成测试。

scala.tools.ncs.IMain

你可以调用 REPL来评估代码(如果你想要一些适用于 Scala 2.10的东西,IMain这也可以在上面找到):CompilerMatcher

  val main = new IMain(s) {
    def lastReq = prevRequestList.last
  }
  main.compileSources(files.map(toSourceFile(_)): _*)
  code map { c => main.interpret(c) match {
    case IR.Error => sys.error("Error interpreting %s" format (c))
    case _ => 
  }}
  val holder = allCatch opt {
    main.lastReq.lineRep.call("$result")
  }

这在 2009 年 Josh Suereth的Embedding the Scala Interpreter post 中得到了证明。

于 2013-12-02T07:59:39.520 回答
4

要编译和运行的类(在文件 test.scala 中)

class Test {

   println ("Hello World!")

}

// compileAndRun.scala (在同一目录中)

import scala.tools.nsc._
import java.io._

val g = new Global(new Settings()) 

val run = new g.Run  

run.compile(List("test.scala"))  // invoke compiler. it creates Test.class.

val classLoader = new java.net.URLClassLoader(
    Array(new File(".").toURI.toURL),  // Using current directory.
    this.getClass.getClassLoader)

val clazz = classLoader.loadClass("Test") // load class 

clazz.newInstance  // create an instance, which will print Hello World.
于 2013-12-02T07:52:45.313 回答