Super Joe
Super Joe

Reputation: 33

get case class arguments and types

Looking to be able to retrieve the argument names and types of a case class. I have been able to get names, but not names and types. Here is an attempt I made, it is based off other snippets here on Stackoverflow. The commented out part is something I'd like to do but does not work.

  def getMethods[T: TypeTag] = typeOf[T].members.collect {
    //case m: MethodSymbol if m.isCaseAccessor => (m, classOf[T].getDeclaredField(m).getType())
    case m: MethodSymbol if m.isCaseAccessor => m
  }.toList

  case class Person(name: String, age: Int)

  getMethods[Person]

Remove the comments and comment the line below I get

<console>:13: error: class type required but T found
              case m: MethodSymbol if m.isCaseAccessor => (m, classOf[T].getDeclaredField(m).getType())

I'm looking for something like List(("name", String), ("age", Int)) or anything similar. I suppose scala 2.10 but scala 2.11 would also be fine.

Upvotes: 3

Views: 985

Answers (1)

Binzi Cao
Binzi Cao

Reputation: 1085

import scala.reflect.runtime.{universe => ru}
def getSymbols[T: ru.TypeTag]: List[ru.Symbol] = ru.typeOf[T].members.toList
case class Person(name: String, age: Int)



scala> getSymbols[Person].filter(!_.isMethod).map(x=>x.name->x.info)
res1: List[(reflect.runtime.universe.Symbol#NameType, reflect.runtime.universe.Type)] = List((age ,scala.Int), (name ,String))

Upvotes: 2

Related Questions