简体   繁体   English

Scala在运行时获取构造函数参数

[英]Scala get constructor parameters at runtime

I'm trying to use reflection to get the types of constructor parameters of a class at runtime. 我正在尝试使用反射在运行时获取类的构造函数参数的类型。 The method below is in the abstract superclass. 下面的方法在抽象超类中。 However this.type is not behaving as expected. 但是, this.type类型的行为不符合预期。 Any help would be much appreciated. 任何帮助将非常感激。

  /**
   * Maps constructor field names to types
   *
   * @return Map[String, Type]
   */
  def getParamTypes: Map[String, ru.Type] =
    ru.typeOf[this.type].
      member(ru.termNames.CONSTRUCTOR)
      .asMethod.paramLists(0).
      foldRight(Map(): Map[String, ru.Type])((p, a) => {
        a + (p.name.decodedName.toString -> p.typeSignature)
      })

Method typeOf requires implicit TypeTag . 方法typeOf需要隐式TypeTag You should use TypeTag directly to get type information available only on call-side: 您应该直接使用TypeTag来获取仅在调用方可用的类型信息:

trait Test {
  def getParamTypes(implicit ttag: ru.TypeTag[this.type]) =
    ttag.tpe.
      member(ru.termNames.CONSTRUCTOR).
      asMethod.paramLists(0).
      foldRight(Map(): Map[String, ru.Type])((p, a) => {
        a + (p.name.decodedName.toString -> p.typeSignature)
      })
}

class TestC(i: Int, s: String) extends Test

val t = new TestC(1, "")
t.getParamTypes
// Map[String,Type] = Map(s -> String, i -> Int)

Alternatively you could get Type of this from Class . 或者,您可以从Class获得this Type

trait Test2 {
  def getParamTypes: Map[String, ru.Type] = {
    val clazz = getClass
    val tpe = ru.runtimeMirror(clazz.getClassLoader).classSymbol(clazz).toType
    tpe.
      member(ru.termNames.CONSTRUCTOR).
      asMethod.paramLists(0).
      foldRight(Map(): Map[String, ru.Type])((p, a) => {
        a + (p.name.decodedName.toString -> p.typeSignature)
      })
  }
}

class TestC2(i: Int, s: String) extends Test2

new TestC2(1, "").getParamTypes
// Map[String,Type] = Map(s -> String, i -> Int)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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