J.Done
J.Done

Reputation: 3053

Scala - Get type of class member

I need to get class' name and type.

I tried with this code.

  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

          //}
      }
  }

result

value types => types / String

value num => num / scala.Int

value name => name / String

I can get all name and types but cannot give condition with type because of String type's value. Any Idea of this?

Upvotes: 0

Views: 1354

Answers (1)

chengpohi
chengpohi

Reputation: 14227

You should use typeOf to get the String type, like:

x.typeSignature =:= typeOf[String]

=:= is used to see if both denote the exact same compile-time type. http://docs.scala-lang.org/overviews/reflection/symbols-trees-types.html

For your compare Int, you should also compare like the x.typeSignature =:= typeOf[Int], compare scala.Int directly, you will get the below warning:

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

Upvotes: 3

Related Questions