4

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.

Charles
  • 50,943
  • 13
  • 104
  • 142
NightWolf
  • 7,694
  • 9
  • 74
  • 121
  • Sorry, I deleted my answer. I realised you are looking for a solution in 2.10 not 2.11 – SpaceMonkey May 05 '14 at 12:49
  • Have you seen this http://stackoverflow.com/questions/11020746/get-companion-object-instance-with-new-scala-reflection-api – Anton May 05 '14 at 15:09

1 Answers1

3

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
som-snytt
  • 39,429
  • 2
  • 47
  • 129