I have the following code and I would like to compile it on the fly and run it.
object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello, world!")
}
}
So far I have tried something like below:
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)
}
}
After toolbox.compile(tree)
I am not able to get the Class
object of the compiled code.
Aucun commentaire:
Enregistrer un commentaire