Reputation: 5962
For Case Class:
case class MyClass(param1: String, param2: String)
Why does this reflective method:
import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.reflect.runtime.{ universe => ru }
def getSettings[T](paramObj: T)(implicit tag: TypeTag[T]) {
val m = ru.runtimeMirror(getClass.getClassLoader)
val classType = ru.typeOf[T].typeSymbol.asClass
val cm = m.reflectClass(classType)
val constructor = tag.tpe.declaration(ru.nme.CONSTRUCTOR).asMethod
val constructorMethod = cm.reflectConstructor(constructor)
val args = constructor.asMethod.paramss.head map { p => (p.name.decoded, p.typeSignature) }
println(args)
}
When Invoked like so:
scala> getSettings(MyClass)
List()
Have that output?? Is the constructor not 2 arguments?? I must be missing something really obvious here. The documentation doesn't cover scenarios quite like this.
http://docs.scala-lang.org/overviews/reflection/overview.html
Upvotes: 4
Views: 1331
Reputation: 38045
getSettings(MyClass)
MyClass
is the companion object of class MyClass
. It has no constructor parameters.
You should rewrite your code like this:
def getSettings[T]()(implicit tag: TypeTag[T]) {
...
}
scala> getSettings[MyClass]
List((param1,String), (param2,String))
Upvotes: 2