2008-10-10 42 views

回答

6

注意:这个答案已经过时!

使用TypeTag斯卡拉2.10及以上,请参阅答案

我可以向您推荐#Scala freenode上

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. 

+0

的人有非常好的! – svrist 2008-10-10 09:00:02

+1

这是错误的。请参阅关于清单的回答 – Alexey 2010-04-25 15:19:46

2

请注意,这是不是真的“的事:“

object Test { 
    def main (args : Array[String]) { 
    println(classOf[List[String]]) 
    } 
} 

$ scala Test      
class scala.List 

我想你可以删除怪这个

==== ====编辑 我已经试过的方法有泛型类型参数做:

object TestSv { 
    def main(args:Array[String]){ 
    narf[String] 
    } 
    def narf[T](){ 
    println(classOf[T]) 
    } 
} 

而编译器不会接受它。类型arn't类是解释

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) 
} 

AnyRef绑定就在那里以确保该值具有.toString方法。

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] 
相关问题