【发布时间】:2019-09-16 21:56:29
【问题描述】:
我有以下代码,我想即时编译并运行它。
object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello, world!")
}
}
到目前为止,我已经尝试过以下方法:
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
object MainScala {
def main(args: Array[String]): Unit = {
val toolbox = currentMirror.mkToolBox()
val source =
"""
|object HelloWorld {
| def main(args: Array[String]): Unit = {
| println("Hello, world!")
| }
|}
|""".stripMargin
val tree = toolbox.parse(source)
val binary = toolbox.compile(tree)
var c = binary.getClass
val m = c.getMethod("main", classOf[Array[String]])
val params = Array("Apple", "Banana", "Orange")
m.invoke(null, null)
}
}
toolbox.compile(tree) 之后我无法获取编译后代码的Class 对象。
【问题讨论】:
标签: scala reflection scala-reflect scala-compiler