Scala反射:如何通过反射找到无参数构造函数(如果有多个构造函数)?“签名”的类型是什么;没有arg;?

Scala反射:如何通过反射找到无参数构造函数(如果有多个构造函数)?“签名”的类型是什么;没有arg;?,scala,reflection,Scala,Reflection,我希望以反射方式创建给定对象的副本(该对象称为根对象) 为此,我需要创建root类的实例 我试过了在会议上提出的建议 但它不适用于具有多个构造函数的对象 如何找到无参数构造函数 我的猜测是,我应该使用类似于asTerm.alternations.filter(u.typeSignature==???)的方法来查找无参数构造函数,但我不确定,这是正确的方法吗 即使是这样,如果我正在寻找一个无参数构造函数,我也不知道应该用什么来代替? 换句话说,无参数构造函数的类型签名是什么 在下面的代码中,r

我希望以反射方式创建给定对象的副本(该对象称为
根对象

为此,我需要创建
root
类的实例

我试过了在会议上提出的建议 但它不适用于具有多个构造函数的对象

  • 如何找到无参数构造函数

  • 我的猜测是,我应该使用类似于
    asTerm.alternations.filter(u.typeSignature==???)
    的方法来查找无参数构造函数,但我不确定,这是正确的方法吗

  • 即使是这样,如果我正在寻找一个无参数构造函数,我也不知道应该用什么来代替

  • 换句话说,无参数构造函数的类型签名是什么

在下面的代码中,
root
是一个对象,我不想找到它的arg构造函数

守则:

  val m= runtimeMirror(getClass.getClassLoader)
  val rootsMirror: InstanceMirror =m.reflect(root)
  val theType: Type =m.reflect(root).symbol.toType
  val classSymbol : ClassSymbol =m.reflect(root).symbol
  val classMirror:ClassMirror=m.reflectClass(classSymbol)
  val constructorMirror: MethodMirror = classMirror.reflectConstructor(
    theType.declaration(nme.CONSTRUCTOR).asTerm.alternatives.filter(_.typeSignature== ???))
比如:

scala> class X(i: Int) { def this() = this(1) }
defined class X

scala> typeOf[X].declarations.filter { s => s.isMethod && {
     | val m = s.asMethod
     | m.isConstructor && m.paramss.flatten.isEmpty }}
res2: Iterable[reflect.runtime.universe.Symbol] = SynchronizedOps(constructor X)
与类型略有不同:

scala> res5 filter (_ match { case MethodType(ps, t) if ps.isEmpty => true case _ => false })
res7: Iterable[reflect.runtime.universe.Type] = List(()X)