【问题标题】:Getting the string representation of a type at runtime in Scala在 Scala 中在运行时获取类型的字符串表示
【发布时间】:2010-09-16 11:08:05
【问题描述】:

在 Scala 中,是否可以在运行时获取类型的字符串表示形式?我正在尝试按照以下方式做一些事情:

def printTheNameOfThisType[T]() = {
  println(T.toString)
}

【问题讨论】:

    标签: scala types


    【解决方案1】:

    在 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]
    

    【讨论】:

      【解决方案2】:

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

      请使用 Scala 2.10 及更高版本的 TypeTag 查看答案

      我可以在 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.
      

      Description of classOf

      【讨论】:

      • 那里的人真的很好!
      【解决方案3】:

      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 方法。

      【讨论】:

      • 如果没有值参数t,这似乎对我不起作用
      • 如果使用 scala 2.10 及以上版本,您可以使用 TypeTag 代替。参考TypeTag答案。
      【解决方案4】:

      请注意,这并不是真正的“事情:”

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

      编译器不会接受它。类型不是类是解释

      【讨论】:

        猜你喜欢
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-21
        相关资源
        最近更新 更多