jhegedus
jhegedus

Reputation: 20653

Scala Reflection: How to find a no-arg constructor via reflection (if there are multiple constructors) ? What is the type signature of "no-arg"?

I want to create reflectively a copy of a given object (this object is called root).

For that I need to create an instance of the class of root.

I tried the advice given at http://docs.scala-lang.org/overviews/reflection/overview.html but it does not work for objects that have several constructors.

In the code below root is the object whose no-arg constructor I'd like to find.

The code:

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

Upvotes: 2

Views: 312

Answers (1)

som-snytt
som-snytt

Reputation: 39577

Something like:

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)

A little different, from the types:

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

Upvotes: 3

Related Questions