我想知道是否有可能做以下事情:
import scala.reflect.runtime.universe._
class Bar[T]
def foo[T]()(implicit ctag: reflect.ClassTag[T]) {
val clazz = classOf[Bar[ctag.runtimeClass.asInstanceOf[Class[T]]]]
}
Run Code Online (Sandbox Code Playgroud)
这里Scala编译器抱怨:
error: stable identifier required, but ctag.runtimeClass found.
Run Code Online (Sandbox Code Playgroud)
有没有办法从函数中可用的运行时类型信息中插入类型参数的类类型?
有没有办法从函数中可用的运行时类型信息中插入类型参数的类类型?
classOf[Bar[T]]工作原因很简单:它不会插入任何运行时信息!classOf[Bar[T]],classOf[Bar[String]],classOf[Bar[Int]],classOf[Bar[_]]都是一样的; 这就是JVM上下文中类型擦除的含义(为了避免误导,我更愿意classOf[Bar[_]]在可能的情况下使用).请注意,其实是有一个例外:如果Bar是Array的,因为classOf[Array[Int]]和classOf[Array[Object]](EG)是不同的!
classOf[T] 显然需要运行时信息,所以它不起作用.