Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - how to get the 'type' for a field using reflection api

I am using Scala 2.11.0-M5.

I need to find the fields (members that are vars or vals) of a Scala class/type and for each field I need to find the class/type.

So far I have been able to get the field members but I can't figure out how to get the member's type once I have the member.

scala> class Account {
  var name: String = null;
  var accountNumber: String = null;
}     |      |      | 
defined class Account

scala> import reflect.runtime.universe._
import reflect.runtime.universe._

scala> for (m <- typeOf[Account].members.filter(m => !m.isMethod)) {
 |   println(m)
 |   // ??? how do I get the member's type ????
 | }
variable accountNumber
variable name
like image 653
Chris W Avatar asked Feb 15 '23 00:02

Chris W


1 Answers

You can use typeSignature:

scala> typeOf[Account].members.filter(!_.isMethod).foreach(
 |   sym => println(sym + " is a " + sym.typeSignature)
 | )
variable accountNumber is a String
variable name is a String

In this context this method will return a reflect.runtime.universe.Type.

like image 104
Travis Brown Avatar answered May 07 '23 21:05

Travis Brown