【问题标题】:How to get the actual type of a generic type?如何获取泛型类型的实际类型?
【发布时间】:2011-03-23 03:01:01
【问题描述】:

有一个具有泛型类型的类:

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?
}

【问题讨论】:

  • 我们在说什么语言?
  • 你能用action.getClass()吗?
  • action.getClass 无法分辨实际类型

标签: generics scala


【解决方案1】:

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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 2013-09-13
    • 2019-01-20
    • 2015-11-20
    • 1970-01-01
    相关资源
    最近更新 更多