在Scala中,是否可以在运行时获取类型的字符串表示形式?我试图沿着这些方向做点什么:
def printTheNameOfThisType[T]() = {
println(T.toString)
}
Run Code Online (Sandbox Code Playgroud)
在Scala 2.10及更高版本中,使用TypeTag包含完整类型信息的内容.您需要包含scala-reflect库才能执行此操作:
import scala.reflect.runtime.universe._
def printTheNameOfThisType[T: TypeTag]() = {
println(typeOf[T].toString)
}
Run Code Online (Sandbox Code Playgroud)
您将获得如下结果:
scala> printTheNameOfThisType[Int]
Int
scala> printTheNameOfThisType[String]
String
scala> printTheNameOfThisType[List[Int]]
scala.List[Int]
Run Code Online (Sandbox Code Playgroud)
请使用TypeTag for Scala 2.10及更高版本查看答案
我可以在freenode上推荐#Scala
10:48 <seet_> http://stackoverflow.com/questions/190368/getting-the-string-representation-of-a-type-at-runtime-in-scala <-- isnt this posible?
10:48 <seet_> possible
10:48 <lambdabot> Title: Getting the string representation of a type at runtime in Scala - Stack Overflow,
http://tinyurl.com/53242l
10:49 <mapreduce> Types aren't objects.
10:49 <mapreduce> or values
10:49 <mapreduce> println(classOf[T]) should give you something, but probably not what you want.
Run Code Online (Sandbox Code Playgroud)
小智 6
在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)
}
Run Code Online (Sandbox Code Playgroud)
AnyRef绑定就是为了确保该值具有.toString方法.
| 归档时间: |
|
| 查看次数: |
6241 次 |
| 最近记录: |