Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get case class arguments and types

Tags:

scala

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.

like image 471
Super Joe Avatar asked Jan 18 '26 03:01

Super Joe


1 Answers

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))
like image 61
Binzi Cao Avatar answered Jan 20 '26 19:01

Binzi Cao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!