Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Scala反射查找最派生的运行时类型_Scala_Reflection - Fatal编程技术网

使用Scala反射查找最派生的运行时类型

使用Scala反射查找最派生的运行时类型,scala,reflection,Scala,Reflection,我试图使用Scala 2.10反射来查找方法参数的最派生类型。例如,考虑这个程序: import reflect.runtime.universe._ object ReflectionTest { def checkType[A : TypeTag](item: A) { println("typeOf[A]: " + typeOf[A]) } def main(args: Array[String]) { val a = Array(1, "Hello")

我试图使用Scala 2.10反射来查找方法参数的最派生类型。例如,考虑这个程序:

import reflect.runtime.universe._

object ReflectionTest {

  def checkType[A : TypeTag](item: A) {
    println("typeOf[A]: " + typeOf[A])
  }

  def main(args: Array[String]) {
    val a = Array(1, "Hello")
    for (item <- a) checkType(item)
  }
}
这对我来说很有意义,因为TypeTag是由编译器在调用时生成的(它只知道类型是
Any
)。然而,我想要的是确定每个项目的实际类型。我想输出一些与

Int
String
我已经看过这里的文件了


但这些样本似乎没有涵盖这个案例,我发现那里关于环境、宇宙和镜子的讨论很难深入。看起来我想做的应该很简单,但也许我完全错了。

最明显的解决方案是使用类:

def checkType[A](item: A) {
  println("typeOf[A]: " + item.getClass)
}
但是,如果要使用
类型
,则需要进行一些额外的工作:

def checkType[A](item: A) {
  val mirror = runtimeMirror(this.getClass.getClassLoader)
  println("typeOf[A]: " + mirror.classSymbol(item.getClass).toType)
}

谢谢,@tenshi,这很有帮助。实际上,我正试图用数组来实现这一点。我注意到您的解决方案似乎返回已擦除的类型。我还需要访问数组的元素类型。我不确定是否有一个简单的解决方法。。。我将继续挖掘。如果没有某种编译时信息(类型标记),您无法从反射中检索未擦除的类型,因为JVM上在运行时只存在已擦除的类型,因此@tenshi的答案是最好的。唯一的方法是将数组中每个元素的类型标记存储在与此数据结构相邻的另一个数据结构中。
def checkType[A](item: A) {
  val mirror = runtimeMirror(this.getClass.getClassLoader)
  println("typeOf[A]: " + mirror.classSymbol(item.getClass).toType)
}