如何使用 TypeTag
获取包括泛型在内的简单类名称?我认为方法签名应该是这样的:
def getClassName[A: TypeTag](a: A): String
getClassName(Map("a"-> 123))
应返回 Map[String,Int]
。
我尝试过的事情:
def getClassName[A: TypeTag](a: A): String = {
typeOf[A].typeSymbol.name.toString
}
scala> getClassName(Map("a" -> 123))
res1: String = Map
def getClassName[A: TypeTag](a: A): String = {
typeOf[A].typeSymbol.toString
}
scala> getClassName(Map("a" -> 123))
res1: String = trait Map
def getClassName[A: TypeTag](a: A): String = {
typeOf[A].toString
}
scala> getClassName(Map("a" -> 123))
res1: String = scala.collection.immutable.Map[String,Int] // It knows the full type!
def getClassName[A: TypeTag](a: A): String = {
typeOf[A].typeSymbol.fullName
}
scala> getClassName(Map("a" -> 123))
res1: String = scala.collection.immutable.Map
最佳答案
从这里:https://docs.scala-lang.org/overviews/reflection/typetags-manifests.html
import scala.reflect.runtime.universe._
def getClassName[T](x: T)(implicit tag: TypeTag[T]): String = {
tag.tpe match { case TypeRef(_, t, args) => s"""${t.name} [${args.mkString(",")}]""" }
}
getClassName(Map("a" -> 123))
res5: String = Map [java.lang.String,Int]
更新:带有完整类名的较短版本
def getClassName[T: TypeTag](x: T) = typeOf[T].toString
getClassName(Map("a" -> 123))
res1: String = scala.collection.immutable.Map[java.lang.String,Int]
关于scala - 如何从 scala TypeTag 获取通用简单类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60721147/