简体   繁体   中英

How to get constructor arguments in a method using typetags/mirrors?

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM