如何获取泛型类型的实际类型?
有一个具有泛型类型的类:
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?
}
There is a class with generic type:
class Action[T]
Create some instances of it, put in a list:
val list = List(new Action[String], new Action[Int])
Iterate it, and how to get the actual type of the instances?
list foreach { action =>
// how do I know the action is for a String or an Int?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Scala 在编译时会删除泛型类型参数,因此除了传统反射提供的内容之外,您还需要在对象中提供一些其他证据。请参阅:
如何解决 Scala 上的类型擦除问题?或者,为什么我无法获取集合的类型参数?
这个问题似乎暗示在某些情况下可能有一些魔法可以应用:
计算 Scala 泛型类“equals”方法中的类型参数...是唯一的方式?
Scala erases generic type parameters at compilation, so you would need to have some additional evidence in you object other than what traditional reflection provides. See:
How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?
This questions seems to imply there might be some magic to apply in some circumstances:
Accounting for type parameters in a Scala generic class 'equals' method... are manifests the only way?