在运行时编译和执行Scala代码

问题描述:

在Scala或Java中是否可以在运行时以字符串形式编译和执行Scala代码?

Is is possible to compile and execute scala code as a string at runtime either in Scala or in Java?

我的想法是使用Scala构建DSL,然后让Java程序员在Java内部使用DSL。

My idea is to build a DSL using Scala then let Java programmers use the DSL inside Java.

我听说scala.tools.nsc.Interpreter类可以执行类似的操作,但是当我将其导入scala文件时,出现了对象工具不是包scala的成员。

I heard that the class scala.tools.nsc.Interpreter can do something like that, but when I imported it inside my scala file, I got "object tools is not a member of package scala."

那么有人可以给我一个提示吗?

So could anybody give me a hint?

在2.10.0中,我们公开了Scala反射API,其中包括运行时编译工具。可在此处找到更多详细信息:从字符串生成一个类,并在Scala 2.10中实例化它。

In 2.10.0 we expose Scala reflection API, which among everything else includes a runtime compilation facility. More details can be found here: Generating a class from string and instantiating it in Scala 2.10.