Scala 如何找到与特定签名匹配的重载方法?

Scala 如何找到与特定签名匹配的重载方法?,scala,reflection,Scala,Reflection,我试图找到一个与给定var args参数匹配的任意类的构造函数。不幸的是,我进展甚微,因为我很难理解Scala的反射API。检索所有可用构造函数的列表后,我无法识别与可用参数匹配的构造函数 private lazy val `class` = mirror.staticClass( "myPackage.myClass" ) protected def reflect( arguments: Any* ): T = { val constructor = `class`

我试图找到一个与给定var args参数匹配的任意类的构造函数。不幸的是,我进展甚微,因为我很难理解Scala的反射API。检索所有可用构造函数的列表后,我无法识别与可用参数匹配的构造函数

private lazy val `class` = mirror.staticClass( "myPackage.myClass" )

protected def reflect( arguments: Any* ): T =
{
    val constructor = `class`
        .toType
        .members
        .collect{ case method: MethodSymbol if method.isConstructor => method }
        .collectFirst[MethodSymbol]{ case _ => null  } // ???
        .getOrElse( throw new RuntimeException( "No valid constructor given" ) )

    mirror
        .reflectClass( `class` )
        .reflectConstructor( constructor )
        .apply( arguments: _* )
        .asInstanceOf[T]
}

我在我的博客文章中谈到了这一点。MethodSymbol有一个类型签名,我们可以从中评估事物。例如,在post中,下面的方法将获得对象的所有Int返回方法:

def intMethods[T : TypeTag](v: T) = {
  val IntType = typeOf[Int]
  val vType   = typeOf[T]
  val methods = vType.members.collect {
    case m: MethodSymbol if !m.isPrivate => m -> m.typeSignatureIn(vType)
  }
  methods collect {
    case (m, mt @ NullaryMethodType(IntType))          => m -> mt
    case (m, mt @ MethodType(_, IntType))              => m -> mt
    case (m, mt @ PolyType(_, MethodType(_, IntType))) => m -> mt
  }
}

我在我的博客文章中谈到了这一点。MethodSymbol有一个类型签名,我们可以从中评估事物。例如,在post中,下面的方法将获得对象的所有Int返回方法:

def intMethods[T : TypeTag](v: T) = {
  val IntType = typeOf[Int]
  val vType   = typeOf[T]
  val methods = vType.members.collect {
    case m: MethodSymbol if !m.isPrivate => m -> m.typeSignatureIn(vType)
  }
  methods collect {
    case (m, mt @ NullaryMethodType(IntType))          => m -> mt
    case (m, mt @ MethodType(_, IntType))              => m -> mt
    case (m, mt @ PolyType(_, MethodType(_, IntType))) => m -> mt
  }
}