【问题标题】:Scala - Get type of class memberScala - 获取类成员的类型
【发布时间】:2016-11-02 14:45:54
【问题描述】:

我需要获取班级的名称和类型。

我尝试使用此代码。

  case class test( name: String, num: Int, types: String)

  ru.typeOf[ test].members.foreach { x =>
      if( !x.isMethod)
      {
          println( x + " => " + x.name + " / " + x.typeSignature) 
          if( x.typeSignature == scala.Int) {

          }
          //if( x.typeSignature == java.lang.String) { // object java.lang.String is not a value

          //}
      }
  }

结果

值类型 => 类型/字符串

值 num => num / scala.Int

值名称 => 名称/字符串

我可以获取所有名称和类型,但由于 String 类型的值,我无法使用类型给出条件。有什么想法吗?

【问题讨论】:

    标签: scala types


    【解决方案1】:

    您应该使用typeOf 来获取String 类型,例如:

    x.typeSignature =:= typeOf[String]
    

    =:= 用于查看两者是否表示完全相同的编译时类型。 http://docs.scala-lang.org/overviews/reflection/symbols-trees-types.html

    为了你的比较Int,你也应该像x.typeSignature =:= typeOf[Int]一样比较,直接比较scala.Int,你会得到以下警告:

    <console>:18: warning: reflect.runtime.universe.Type and Int.type are unrelated: they will most likely never compare equal
           res23.typeSignature == scala.Int
    

    【讨论】:

    • 我收到“未找到:值类型”错误。我应该导入一些包吗?
    • @J.Done,对于您的代码示例,您应该使用ru.typeOf[String]
    • 或者你可以import ru._
    猜你喜欢
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 2018-10-01
    • 1970-01-01
    • 2021-11-27
    • 2011-01-30
    相关资源
    最近更新 更多