Reputation: 20653
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.
How can I locate the no-arg constructor ?
My guess is that I should use something like asTerm.alternatives.filter(_.typeSignature== ???))
to find the no-arg constructor but I am not sure, is this the correct approach ?
Even if this is the way to go, I have no idea what should go in place of ???
if I am looking for a no-arg constructor ?
In other words, what is the type signature of a no-arg constructor ?
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
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