samedi 28 novembre 2015

Scala object reference with reflection

I'm new to the reflection API.

I'd like to get a reference to an object from its name. I've made it to the point where I can get a reference using the class name of the object.

$ scala
Welcome to Scala version 2.11.7 ...

scala> case object Foo { val x = 5 }
defined object Foo

scala> import scala.reflect.runtime.{universe => ru}
import scala.reflect.runtime.{universe=>ru}

scala> val m = ru.runtimeMirror(getClass.getClassLoader)
m: reflect.runtime.universe.Mirror...

scala> val f = m.reflectModule(m.staticModule(Foo.getClass.getName)).instance.asInstanceOf[Foo.type]
f: Foo.type = Foo

scala> f.x
res0: Int = 5

Works just fine. However, trying to use the computed type name as a string doesn't work:

scala> m.staticModule(Foo.getClass.getName)
res2: reflect.runtime.universe.ModuleSymbol = object iw$Foo$

scala> Foo.getClass.getName
res1: String = Foo$

scala> m.staticModule("Foo$")
scala.ScalaReflectionException: object Foo$ not found.
  at scala.reflect.internal.Mirrors$RootsBase.staticModule(Mirrors.scala:162)
  at scala.reflect.internal.Mirrors$RootsBase.staticModule(Mirrors.scala:22)
  ... 33 elided

I would expect the following to work

scala> val f = m.reflectModule(m.staticModule("Foo$").instance.asInstance

What am I missing here? Thanks.





Aucun commentaire:

Enregistrer un commentaire