在Scala中,是否可以在运行时获取类型的字符串表示形式?我试图沿着这些方向做点什么:
def printTheNameOfThisType[T]() = { println(T.toString) }
Julie.. 8
在Scala 2.10及更高版本中,使用TypeTag
包含完整类型信息的内容.您需要包含scala-reflect
库才能执行此操作:
import scala.reflect.runtime.universe._ def printTheNameOfThisType[T: TypeTag]() = { println(typeOf[T].toString) }
您将获得如下结果:
scala> printTheNameOfThisType[Int] Int scala> printTheNameOfThisType[String] String scala> printTheNameOfThisType[List[Int]] scala.List[Int]
svrist.. 6
注意:这个答案已经过时了!
请使用TypeTag for Scala 2.10及更高版本查看答案
我可以在freenode上推荐#Scala
10:48http://stackoverflow.com/questions/190368/getting-the-string-representation-of-a-type-at-runtime-in-scala <-- isnt this posible? 10:48 possible 10:48 Title: Getting the string representation of a type at runtime in Scala - Stack Overflow, http://tinyurl.com/53242l 10:49 Types aren't objects. 10:49 or values 10:49 println(classOf[T]) should give you something, but probably not what you want.
classOf的描述
在Scala 2.10及更高版本中,使用TypeTag
包含完整类型信息的内容.您需要包含scala-reflect
库才能执行此操作:
import scala.reflect.runtime.universe._ def printTheNameOfThisType[T: TypeTag]() = { println(typeOf[T].toString) }
您将获得如下结果:
scala> printTheNameOfThisType[Int] Int scala> printTheNameOfThisType[String] String scala> printTheNameOfThisType[List[Int]] scala.List[Int]
请使用TypeTag for Scala 2.10及更高版本查看答案
我可以在freenode上推荐#Scala
10:48http://stackoverflow.com/questions/190368/getting-the-string-representation-of-a-type-at-runtime-in-scala <-- isnt this posible? 10:48 possible 10:48 Title: Getting the string representation of a type at runtime in Scala - Stack Overflow, http://tinyurl.com/53242l 10:49 Types aren't objects. 10:49 or values 10:49 println(classOf[T]) should give you something, but probably not what you want.
classOf的描述
在Scala中有一个新的,大多数没有记录的功能,称为"清单"; 它的工作原理如下:
object Foo { def apply[T <: AnyRef](t: T)(implicit m: scala.reflect.Manifest[T]) = println("t was " + t.toString + " of class " + t.getClass.getName() + ", erased from " + m.erasure) }
AnyRef绑定就是为了确保该值具有.toString方法.