【问题标题】:I want to get the type of a variable at runtime我想在运行时获取变量的类型
【发布时间】:2021-05-18 19:10:06
【问题描述】:

我想在运行时获取变量的类型。 我该怎么做?

【问题讨论】:

    标签: scala reflection


    【解决方案1】:

    所以,严格来说,“变量的类型”总是存在的,并且可以作为类型参数传递。例如:

    val x = 5
    def f[T](v: T) = v
    f(x) // T is Int, the type of x
    

    但根据你想做什么,这对你没有帮助。例如,可能不想知道变量的类型是什么,但想知道 value 的类型是否是某个特定类型,例如:

    val x: Any = 5
    def f[T](v: T) = v match {
      case _: Int    => "Int"
      case _: String => "String"
      case _         => "Unknown"
    }
    f(x)
    

    在这里,变量Any 的类型无关紧要。重要的是,检查的是5 的类型,值。事实上,T 是没有用的——你还不如写成def f(v: Any)。此外,这使用ClassTag 或值的Class,如下所述,并且无法检查类型的类型参数:您可以检查某物是否为List[_](某物的List),但不是例如,是 List[Int] 还是 List[String]。

    另一种可能性是您想要reify变量的类型。也就是说,您希望将类型转换为一个值,以便您可以存储它、传递它等等。这涉及到反射,您将使用ClassTag 或TypeTag。例如:

    val x: Any = 5
    import scala.reflect.ClassTag
    def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
    f(x) // returns the string "Any"
    

    ClassTag 还允许您使用在 match 上收到的类型参数。这行不通:

    def f[A, B](a: A, b: B) = a match {
      case _: B => "A is a B"
      case _ => "A is not a B"
    }
    

    但这会:

    val x = 'c'
    val y = 5
    val z: Any = 5
    import scala.reflect.ClassTag
    def f[A, B: ClassTag](a: A, b: B) = a match {
      case _: B => "A is a B"
      case _ => "A is not a B"
    }
    f(x, y) // A (Char) is not a B (Int)
    f(x, z) // A (Char) is a B (Any)
    

    这里我使用 上下文边界 语法 B : ClassTag,它的工作原理与前面 ClassTag 示例中的隐式参数一样,但使用的是匿名变量。

    也可以从值的Class 中获取ClassTag,如下所示:

    val x: Any = 5
    val y = 5
    import scala.reflect.ClassTag
    def f(a: Any, b: Any) = {
      val B = ClassTag(b.getClass)
      ClassTag(a.getClass) match {
        case B => "a is the same class as b"
        case _ => "a is not the same class as b"
      }
    }
    f(x, y) == f(y, x) // true, a is the same class as b
    

    ClassTag 的限制在于它仅涵盖基类,但不涵盖其类型参数。也就是说,List[Int] 和 List[String] 的 ClassTag 是相同的,List。如果您需要类型参数,则必须改用TypeTag。然而,TypeTag 不能从值中获取,也不能用于模式匹配,因为 JVM 的 erasure。

    TypeTag 的示例可能会变得相当复杂——甚至不比较两个类型标签也不是很简单,如下所示:

    import scala.reflect.runtime.universe.TypeTag
    def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
    type X = Int
    val x: X = 5
    val y = 5
    f(x, y) // false, X is not the same type as Int
    

    当然,有一些方法可以使这种比较返回真实,但它需要几本书的章节才能真正涵盖TypeTag,所以我会在这里停下来。

    最后,也许你根本不关心变量的类型。也许你只是想知道一个值的类是什么,在这种情况下答案很简单:

    val x = 5
    x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it
    

    不过,最好能更具体地说明您想要完成的任务,以便答案更中肯。

    【讨论】:

    • 您在“但这将:”之后编写的示例代码令人困惑。它可以编译,但结果不是您在 cmets 中显示的结果。两个调用都返回相同的结果:“A 是 B”。因为值5 既是Int 的实例又是Any 的实例。除此之外,你的解释很完美:)
    • @Readren 该值未经测试,类是。 Int 是 Any,但 Any 不是 Int。它适用于 Scala 2.10,它应该适用于 Scala 2.11,但我不知道为什么它不是。
    • 和你这样的大佬相矛盾让我害怕,但是代码a match { case _: B => ...测试的是变量a的实际值的类型,而不是变量a的类型。你是对的,它返回你在 scala 2.10.6 中所说的内容。但这应该是一个错误。在 scala 2.11.8 中,实际值的类型被测试了,因为它应该。
    • 非常好的关于 ClassTag 和 TypeTag 之间差异的报道,正是我想要的。
    • 有没有办法对这个进行空检查?
    【解决方案2】:

    我认为这个问题不完整。如果你的意思是你想得到某个类型类的类型信息,那么下面:

    如果您希望按照您指定的方式打印,那么:

    scala>  def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
    manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]
    
    scala> val x = List(1,2,3)
    x: List[Int] = List(1, 2, 3)
    
    scala> println(manOf(x))
    scala.collection.immutable.List[Int]
    

    如果你是repl模式,那么

    scala> :type List(1,2,3)
    List[Int]
    

    或者,如果您只是想知道类类型,那么正如@monkjack 解释的那样,"string".getClass 可能会解决问题

    【讨论】:

    • 给读者:这是最有用的解决方案。与 Javascript typeof x 一样,这里 manOf(x) 说数据类型!
    【解决方案3】:

    如果变量的类型是指变量指向的对象的运行时类,那么你可以通过所有对象都有的类引用来获得。

    val name = "sam";
    name: java.lang.String = sam
    name.getClass
    res0: java.lang.Class[_] = class java.lang.String
    

    但是,如果您的意思是变量被声明为的类型,那么您将无法理解。例如,如果你说

    val name: Object = "sam"
    

    那么你仍然会从上面的代码中得到一个String。

    【讨论】:

    • 您也可以使用name.getClass.getSimpleName 以获得更易读的输出
    【解决方案4】:

    我已经测试过了,它确实有效

    val x = 9
    def printType[T](x:T) :Unit = {println(x.getClass.toString())}
    

    【讨论】:

    • 它不告诉类的子类型。如上所述,对于 List[String] 和 List[int] ,它将返回相同的内容: List
    【解决方案5】:
    instance.getClass
    

    上面实例类的方法返回路径。 要获取实例的确切类名称,请尝试以下操作:

    instance.getClass.getSimpleName
    

    示例如下:

    【讨论】:

      猜你喜欢
      • 2011-12-31
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多