Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created February 5, 2013 10:39
Show Gist options
  • Select an option

  • Save debasishg/4713638 to your computer and use it in GitHub Desktop.

Select an option

Save debasishg/4713638 to your computer and use it in GitHub Desktop.
Trying to invoke the no-arg constructor - stuck at the last step ..
scala> case class Shop(store: String, item: String, cost: Int) {
| def this() = this(null, null, 0)
| }
defined class Shop
scala> val t = typeOf[Shop]
t: reflect.runtime.universe.Type = Shop
scala> val m = runtimeMirror(getClass.getClassLoader)
m: reflect.runtime.universe.Mirror = JavaMirror with scala.tools.nsc.interpreter
.IMain$TranslatingClassLoader@1645d2a of type class scala.tools.nsc.interpreter.
IMain$TranslatingClassLoader with classpath [(memory)] and parent being scala.to
ols.nsc.util.ScalaClassLoader$URLClassLoader@209711 of type class scala.tools.ns
c.util.ScalaClassLoader$URLClassLoader with classpath [file:/C:/Program%20Files%
20(x86)/Java/jre7/lib/resources.jar,file:/C:/Program%20Files%20(x86)/Java/jre7/l
ib/rt.jar,file:/C:/Program%20Files%20(x86)/Java/jre7/lib/jsse.jar,file:/C:/Progr
am%20Files%20(x86)/Java/jre7/lib/jce.jar,file:/C:/Program%20Files%20(x86)/Java/j
re7/lib/charsets.jar,file:/C:/Program%20Files%20(x86)/Java/jre7/lib/ext/dnsns.ja
r,file:/C:/Program%20Files%20(x86)/Java/jre7/lib/ext/localedata.jar,file:/C:/...
scala> val cls = t.typeSymbol.asClass
cls: reflect.runtime.universe.ClassSymbol = class Shop
scala> val cm = m.reflectClass(cls)
cm: reflect.runtime.universe.ClassMirror = class mirror for Shop (bound to null)
scala> val ctors = t.declaration(nme.CONSTRUCTOR).asTerm.alternatives.map(_.typeSignature)
ctors: List[reflect.runtime.universe.Type] = List((store: String, item: String,
cost: scala.Int)Shop, ()Shop)
scala> ctors.collect {
| case c@MethodType(List(), _) => c
| }
res43: List[reflect.runtime.universe.MethodType] = List(()Shop)
// Now I have the default (no-arg) constructor which I would like to invoke as
val ctorm = cm.reflectConstructor(???) // How do I get a MethodSymbol from res43.head ?
ctorm()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment