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

泛型 – 如何获得泛型类型的实际类型?

发布时间:2020-12-16 19:22:21 所属栏目:安全 来源:网络整理
导读:有一个泛型类: class Action[T] 创建它的一些实例,放入一个列表: val list = List(new Action[String],new Action[Int]) 迭代它,以及如何获得实例的实际类型? list foreach { action = // how do I know the action is for a String or an Int?} 解决方法
有一个泛型类:

class Action[T]

创建它的一些实例,放入一个列表:

val list = List(new Action[String],new Action[Int])

迭代它,以及如何获得实例的实际类型?

list foreach { action =>
     // how do I know the action is for a String or an Int?
}

解决方法

Scala在编译时会删除泛型类型参数,因此除了传统反射提供的内容之外,您还需要在对象中添加一些其他证据.看到:

How do I get around type erasure on Scala? Or,why can’t I get the type parameter of my collections?

这些问题似乎暗示在某些情况下可能会有一些魔力:

Accounting for type parameters in a Scala generic class ‘equals’ method… are manifests the only way?

(编辑:李大同)

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

    推荐文章
      热点阅读