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

末鹿安然 提交于 2019-12-01 06:37:48

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/17177427/how-to-get-constructor-arguments-in-a-method-using-typetags-mirrors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!