如何从 scala TypeTag 中获取通用的简单 class 名称?

How to get generic simple class name from scala TypeTag?

如何使用 TypeTag 获得包含通用名称的简单 class 名称?我认为方法签名应该是这样的:

def getClassName[A: TypeTag](a: A): String

getClassName(Map("a" -> 123)) 应该 return 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]

更新:具有完整 class 名称的较短版本

 def getClassName[T: TypeTag](x: T) = typeOf[T].toString

getClassName(Map("a" -> 123))
res1: String = scala.collection.immutable.Map[java.lang.String,Int]

我将根据 添加我的答案,因为 Scala 似乎没有内置此功能。此方法使用上下文绑定语法而不是隐式参数。

def getClassName[A: TypeTag](a: A): String = {
  val typeArgs = typeOf[A].typeArgs
  s"${typeOf[A].typeSymbol.name}${if (typeArgs.nonEmpty) typeArgs.mkString("[",",", "]") else ""}"
}
scala> getClassName(Map("a" -> 123))
res1: String = Map[String,Int]