Question

I would like to be able to get an instance of a Scala Object from a String specified in config. Say for example I have a config property db.driver = "scala.slick.driver.H2Driver"

I would like to be able to get an instance of this object H2Driver. Obviously I could create a map of configs to actual objects, but that seems like a hassle. I could also do this by including a $ on the end of the config and loading up the module, i.e.

   val cl = Class.forName("scala.slick.driver.H2Driver$") //note the $
   val driverObj = cl.getField("MODULE$").get(null).asInstanceOf[JdbcProfile]

But I was hoping there was a neater way to do this in Scala 2.10 using the newer reflections API.

Was it helpful?

Solution

Same in 2.10:

Welcome to Scala version 2.11.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import reflect.runtime._
import reflect.runtime._

scala> currentMirror staticModule "scala.Array"
res0: reflect.runtime.universe.ModuleSymbol = object Array

scala> currentMirror reflectModule res0
res1: reflect.runtime.universe.ModuleMirror = module mirror for scala.Array (bound to null)

scala> .instance
res2: Any = scala.Array$@67b467e9
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top