如何使用类型标签/镜像在方法中获取构造函数参数? [英] How to get constructor arguments in a method using typetags/mirrors?

查看:32
本文介绍了如何使用类型标签/镜像在方法中获取构造函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于案例类:

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

当这样调用时:

scala> getSettings(MyClass)
List()

有那个输出??构造函数不是 2 个参数吗??我一定在这里遗漏了一些非常明显的东西.该文档并未涵盖此类场景.

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/概览.html

推荐答案

getSettings(MyClass)

MyClassMyClass 类的伴随对象.它没有构造函数参数.

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

这篇关于如何使用类型标签/镜像在方法中获取构造函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆