scala - 解析包含代码的字符串,返回一个 Type

标签 scala reflection scala-2.10

我想解析一段包含在 String 中的 scala 代码并获取结果 reflect.runtime.universe.Type该表达式的(String => Type)。我试过:

scala> import scala.tools.nsc.interpreter.IMain
import scala.tools.nsc.interpreter.IMain

scala> new IMain().exprTyper.parse("scala.Option")
warning: there were 1 feature warning(s); re-run with -feature for details
res1: Option[List[_2.repl.global.Tree]] forSome { val _2: scala.tools.nsc.interpreter.IMain#exprTyper.type } = Some(List(scala.Option))

scala> .get.head
warning: there were 1 feature warning(s); re-run with -feature for details
res2: _2.repl.global.Tree forSome { val _2: scala.tools.nsc.interpreter.IMain#exprTyper.type } = scala.Option

scala> .tpe
res3: _2.type#repl.global.Type = null

scala> new IMain().runtimeTypeOfTerm("scala.Option")
warning: there were 1 feature warning(s); re-run with -feature for details
res5: _74.global.Type forSome { val _74: scala.tools.nsc.interpreter.IMain } = <notype>

scala> new IMain().typeOfTerm("scala.Option")
warning: there were 1 feature warning(s); re-run with -feature for details
res6: _75.global.Type forSome { val _75: scala.tools.nsc.interpreter.IMain } = <notype>

这可能吗?如果可能的话,你是如何做到的?谢谢。

UPD:我已经在这个问题中表达了实际意图以及我现在所处的位置:Getting type information inside scala repl via IMain

最佳答案

因此,在潜伏在 SO 周围之后(特别感谢 this answer ),我收敛到以下结果:

scala> def toType(expr: String): Type = {
     | import scala.tools.reflect.ToolBox
     | import scala.reflect.runtime.{currentMirror => m}
     | val tb = m.mkToolBox()
     | val exp = tb.parse(expr.trim)
     | tb.typeCheck(exp).tpe
     | }
toType: (expr: String)reflect.runtime.universe.Type

scala> toType("Option")
res2: reflect.runtime.universe.Type = Option.type

scala> toType("List")
res3: reflect.runtime.universe.Type = scala.collection.immutable.List.type

关于scala - 解析包含代码的字符串,返回一个 Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15659641/

相关文章:

scala - 我可以在 Scala 中定义和使用类和对象之外的函数吗?

scala - 匿名函数作为参数

scala - DAG、Scala/Akka

java - 如何从 Java 中的类名中获取类对象

unit-testing - 模拟重载方法

scala - 为什么 Scala 的 == 在 Int 的情况下不同?

Scala的带对象+的中缀表示法,为什么不可能呢?

scala - 如何从Gradle执行Scala脚本?

c# - 如何调用带有 out 参数的方法?

c# - 为什么不能使用反射获取局部变量名?