加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

通过Scala 2.10中的反射查找类型参数?

发布时间:2020-12-16 09:39:16 所属栏目:安全 来源:网络整理
导读:使用类型标签,我可以看到一些类型的参数: scala import scala.reflect.runtime.universe._import scala.reflect.runtime.universe._scala typeOf[List[Int]]res0: reflect.runtime.universe.Type = List[Int] 但是我一点也不知道如何通过编程方式把这个“I
使用类型标签,我可以看到一些类型的参数:

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

scala> typeOf[List[Int]]
res0: reflect.runtime.universe.Type = List[Int]

但是我一点也不知道如何通过编程方式把这个“Int”从那里出来。

(我已经在REPL中徘徊了一个小时,尝试排列类型,看看我可以从中获得什么…我收到很多东西,这表明这是一个“列表”,但祝你好运那个“Int”!我真的不想诉诸toString()输出…)

丹尼尔·索布尔(Daniel Sobral)有一个非常好的(一般的)快速概述here,他在其中很接近我正在寻找的东西,但(显然)只有当你知道,对于那个特定的类,一些具体的方法,其类型可以询问:

scala> res0.member(newTermName("head"))
res1: reflect.runtime.universe.Symbol = method head

scala> res1.typeSignatureIn(res0)
res2: reflect.runtime.universe.Type = => Int

但是我希望有一些更通用的东西,它不涉及在声明的方法列表中生根,并希望其中一个将捕获(并因此泄露)标签当前类型的信息。

如果Scala可以轻松打印“List [Int]”,为什么在地球上很难发现“Int”的一部分 – 不诉诸字符串模式匹配?或者我只是错过了一些真正的东西,真的很明显吗?

scala> res0.typeSymbol.asInstanceOf[ClassSymbol].typeParams
res12: List[reflect.runtime.universe.Symbol] = List(type A)

scala> res12.head.typeSignatureIn(res0)
res13: reflect.runtime.universe.Type =

格儿…

解决方法

可悲的是,我不认为有一种方法可以给你参数,但是你可以这样做:

Welcome to Scala version 2.10.0-20121007-145615-65a321c63e (Java HotSpot(TM) 64-Bit Server VM,Java 1.6.0_35).
Type in expressions to have them evaluated.
Type :help for more information.

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

scala> typeOf[List[Int]]
res0: reflect.runtime.universe.Type = scala.List[Int]

scala> res0 match { case TypeRef(_,_,args) => args }
res1: List[reflect.runtime.universe.Type] = List(Int)

scala> res1.head
res2: reflect.runtime.universe.Type = Int

编辑
这是一个稍微更好的方式来实现同样的事情(在discussion on scala-internals之后):

scala> res0.asInstanceOf[TypeRefApi].args
res1: List[reflect.runtime.universe.Type] = List(Int)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读