scala.tools.nsc.Interpreter — How to execute inter

2020-06-17 06:36发布

问题:

I'm experimenting with interpreting strings in Scala to define classes and methods. I used the example from http://scala-programming-language.1934581.n4.nabble.com/Compiling-a-Scala-Snippet-at-run-time-td2000704.html in the following code:

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

It works, but somehow the intepretation results are not happening at the global namespace:

new Test # => <console>:5: error: not found: type Test

Therefore: How to execute interpreter statements so that the results are defined in the global scope? I'm using scala2.7.7final currently, and can't change the interpreter to 2.8.

Thanks for your help

Matthias

回答1:

I think that when you take the step from interpreter to the running application you don't get away from using reflection:

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)

You can still get hold of the class-object and instantiate yourself:

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


回答2:

You can't, because Scala cannot known statically, at compile time, that a class Test will be created by a run-time call.



标签: scala