如何获得泛型类型的实际类型? [英] How to get the actual type of a generic type?

查看:108
本文介绍了如何获得泛型类型的实际类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  class Action [T] 



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

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

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

  list foreach {action => 
//我如何知道该动作是针对String还是Int?

$ / code>


解决方案

编译,所以除了传统反射提供的东西外,您还需要在其中提供一些其他证据。见:

如何解决Scala上的类型擦除问题?或者,为什么我不能获取我的集合的类型参数?



这个问题似乎意味着在某些情况下可能会有一些神奇的应用:




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

解决方案

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?

这篇关于如何获得泛型类型的实际类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆