【问题标题】:TypeTags/Reflection - If I have a Type object, can I get its parameter Type? [duplicate]TypeTags/Reflection - 如果我有一个 Type 对象,我可以得到它的参数 Type 吗? [复制]
【发布时间】:2013-06-20 16:43:16
【问题描述】:

为了简化我的场景, 我有一个类型对象,它是 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 对象中?

【问题讨论】:

  • 宏是编译时间而不是运行时反射
  • @Senia 我需要 typeArgument 的参数。
  • 是的,但是类型 API 完全一样,这就是重点。无论如何,@senia 的链接中的答案会给你类型 String 给定 Some[String] 的类型,我认为这是你需要的?
  • 好的 - 谢谢 - 我会试试看。我发现反射 api 很难导航...感谢您的帮助。

标签: scala reflection scala-2.10


【解决方案1】:

the linked answer 一样,您可以使用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

【讨论】:

  • 非常感谢 - 很抱歉造成混乱。反射 API 不是很容易导航。
猜你喜欢
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
  • 2014-07-23
  • 2015-09-14
  • 1970-01-01
相关资源
最近更新 更多