scala.tools.nsc.Interpreter - 如何执行解释器语句以便在全局范围内定义结果?(Scala 2.7.7final)

Mat*_*her 7 scala

我正在尝试解释Scala中的字符串来定义类和方法.我在以下代码中使用了http://scala-programming-language.1934581.n4.nabble.com/Compiling-a-Scala-Snippet-at-run-time-td2000704.html中的示例:

import scala.tools.nsc.{Interpreter,Settings}
var i = new Interpreter(new Settings(str => println(str)))
i.interpret("class Test { def hello = \"Hello World\"}")
Run Code Online (Sandbox Code Playgroud)

它工作,但不知何故,解释结果不会发生在全局命名空间:

new Test # => <console>:5: error: not found: type Test
Run Code Online (Sandbox Code Playgroud)

因此:如何执行解释器语句以便在全局范围内定义结果?我目前正在使用scala2.7.7final,并且无法将解释器更改为2.8.

谢谢你的帮助

马蒂亚斯

tho*_*dge 6

我认为当你从解释器到正在运行的应用程序采取步骤时,你不会放弃使用反射:

scala> var res = Array[AnyRef](null)
scala> i.bind("result", "Array[AnyRef]", res)
scala> i.interpret("result(0) = new Test")
scala> res
res11: Array[AnyRef] = Array(Test@2a871dcc)
Run Code Online (Sandbox Code Playgroud)

您仍然可以获取类对象并自己实例化:

scala> i.interpret("result(0) = classOf[Test]")                            
scala> res(0).asInstanceOf[Class[_]].getConstructors()(0).newInstance()
res24: Any = Test@28bc917c
Run Code Online (Sandbox Code Playgroud)