简体   繁体   English

如何在运行时获取通用类的TypeTag

[英]How to get TypeTag for generic class at runtime

Assume I have one class defined as below

class[T : ClassTag](val x : Int, val y : T) {

}

I have a utility method to use reflection and constructor parameters and create instance

def createInstance[T : ClassTage](cls : Class[_]) {
     val m = universe.runtimeMirror(getClass.getClassLoader)
    val clsSymbol = m.classSymbol(cls)
    val cm = m.reflectClass(clsSymbol)
    val ctorC = clsSymbol.toType.declaration(universe.nme.CONSTRUCTOR).asMethod
    val ctorm = cm.reflectConstructor(ctorC)

    val fullParams = ctorm.symbol.paramss

constructorFullParams.foreach(map => {
      map.foreach(param => {
        val name = param.name.decodedName.toString
        val ptype = param.typeSignature
        if (ptype.toString == "scala.reflect.ClassTag[T]") {
          //dosth()
        } 
      })
    })
}

as you can see above, I just use the type string value to determine whether the type is a ClassTag and then call dosth() method. 如上所示,我只使用类型字符串值来确定类型是否为ClassTag,然后调用dosth()方法。 it doesn't look good though. 它看起来并不好。 is there any better way to do the checking ? 有更好的检查方法吗?

thanks. 谢谢。

You can make it via typeOf , consider the next code snapshot: 您可以通过typeOf使其实现,请考虑下一个代码快照:

    import scala.reflect.runtime.universe._

    class C[I]

    class A[T: TypeTag] {
      val tpe = typeOf[T]
    }

    val map = new A[Integer]
    val typeC = new A[C[String]]
    println(map.tpe)
    println(typeC.tpe)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM