0

为了简化我的场景,我有一个 Type 对象,它是 Some[String] 或 Some[Int] 或 None。我是否能够获取该 Type 对象并以某种方式将参数 Type 获取到另一个对象中?

例如

scala>  import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> val tt = typeTag[Some[String]]
tt: reflect.runtime.universe.TypeTag[Some[String]] = TypeTag[scala.Some[String]]

scala> val tpe = tt.tpe
tpe: reflect.runtime.universe.Type = scala.Some[String]

所以有你的 Some[String] 类型。如何将参数类型从那里获取到 Type 对象?

4

1 回答 1

1

链接的答案一样,您可以使用TypeRef提取器:

import reflect.runtime.universe._

val tpe = typeOf[Some[String]] // same as typeTag[Some[String]].tpe

// extract type parameters
val TypeRef(_,_, tps) = tpe
// tps has type List[Type]

val innerType = tps.head // <-- here is your type
// innerType: reflect.runtime.universe.Type = String
于 2013-06-20T17:42:59.647 回答